package com.xbongbong.paas.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xbongbong.crm.abstracts.AbstractFineClueService;
import com.xbongbong.crm.help.FineClueHelp;
import com.xbongbong.crm.help.PhoneHelp;
import com.xbongbong.executor.command.FormDataServiceFactory;
import com.xbongbong.executor.command.FormDataUpdateServiceFactory;
import com.xbongbong.formula.constant.Constant;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.outLink.domain.entity.OuterLinkConfigEntity;
import com.xbongbong.outLink.domain.entity.OuterLinkEntity;
import com.xbongbong.paas.business.rule.FormDataActiveRuleHelp;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.data.service.RichTextService;
import com.xbongbong.paas.data.service.SerialNoService;
import com.xbongbong.paas.domain.entity.PaasAppEntity;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.domain.entity.PaasMenuEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.PaasProcessRelatedDataEntity;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.constant.EsNormalConstant;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormDataEsModel;
import com.xbongbong.paas.elasticsearch.model.PaasFormSubDataEsModel;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.pojo.dto.SearchDataInConditionDTO;
import com.xbongbong.paas.elasticsearch.pojo.vo.FormDataRepeatBatchVO;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.ComboTypeEnum;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DefaultTypeEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.SheetTypeEnum;
import com.xbongbong.paas.enums.UnitEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.field.ItemPoJo;
import com.xbongbong.paas.field.LinkConditionPoJo;
import com.xbongbong.paas.field.LinkFormPoJo;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.field.LinkListPojo;
import com.xbongbong.paas.field.LinkedAttrPoJo;
import com.xbongbong.paas.field.MultiUnitItemPoJo;
import com.xbongbong.paas.field.RelyPoJo;
import com.xbongbong.paas.field.SubFormPoJo;
import com.xbongbong.paas.field.UnitItemPoJo;
import com.xbongbong.paas.field.VisibleRulePoJo;
import com.xbongbong.paas.help.CloudCodeHelp;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.parent.help.CommonPermissionHelp;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.help.FormDataListSearchHelp;
import com.xbongbong.paas.help.FormDataValidateProductHelp;
import com.xbongbong.paas.help.FormExplainHelp;
import com.xbongbong.paas.help.PaasFormHelp;
import com.xbongbong.saas.enums.SearchDataFromEnum;
import com.xbongbong.sys.help.PackageHelp;
import com.xbongbong.paas.help.ProFormHelp;
import com.xbongbong.paas.help.ProGetHelp;
import com.xbongbong.paas.help.RepeatHelp;
import com.xbongbong.paas.help.UserHelp;
import com.xbongbong.paas.help.base.BaseLinkBoolQueryBuilderService;
import com.xbongbong.paas.help.service.impl.FormDataLinkDataUpdateGetServiceImpl;
import com.xbongbong.paas.help.subform.TransferSubFormHelper;
import com.xbongbong.paas.help.team.FormTeamSetHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.lowcode.CustomButtonService;
import com.xbongbong.paas.lowcode.LowCodeConfigService;
import com.xbongbong.paas.model.OuterLinkModel;
import com.xbongbong.paas.model.PaasAppModel;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.model.PaasMenuModel;
import com.xbongbong.paas.model.PaasProcessDataModel;
import com.xbongbong.paas.model.PaasProcessRelatedDataModel;
import com.xbongbong.paas.model.PaasProcessTemplateModel;
import com.xbongbong.paas.model.SearchCustomerCompanyModel;
import com.xbongbong.paas.outerlink.interfaces.PaasOuterLinkConfigService;
import com.xbongbong.paas.pojo.ButtonPojo;
import com.xbongbong.paas.pojo.DataDetailPojo;
import com.xbongbong.paas.pojo.DetaPhonePojo;
import com.xbongbong.paas.pojo.DetailTabPojo;
import com.xbongbong.paas.pojo.DetailTitlePojo;
import com.xbongbong.paas.pojo.FieldAttrEntityForMerge;
import com.xbongbong.paas.pojo.FormTitlePoJo;
import com.xbongbong.paas.pojo.HandelDetailPojo;
import com.xbongbong.paas.pojo.ItemDataPoJo;
import com.xbongbong.paas.pojo.MultiUnitPricePoJo;
import com.xbongbong.paas.pojo.OutLinkFieldAttrEntity;
import com.xbongbong.paas.pojo.ProductFieldPojo;
import com.xbongbong.paas.pojo.ShareConditionFormatPojo;
import com.xbongbong.paas.pojo.SummaryDataPoJo;
import com.xbongbong.paas.pojo.WorkFlowPojo;
import com.xbongbong.paas.pojo.dto.ActiveRuleDTO;
import com.xbongbong.paas.pojo.dto.AddBatchDTO;
import com.xbongbong.paas.pojo.dto.AggSumDTO;
import com.xbongbong.paas.pojo.dto.ApprovePrintSubSummaryGetDTO;
import com.xbongbong.paas.pojo.dto.ButtonGetDTO;
import com.xbongbong.paas.pojo.dto.DeleteFormDataByBusinessRuleDTO;
import com.xbongbong.paas.pojo.dto.FormCountGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataAddGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataDeleteDTO;
import com.xbongbong.paas.pojo.dto.FormDataFastAddGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataFastUpdateDTO;
import com.xbongbong.paas.pojo.dto.FormDataGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataListDTO;
import com.xbongbong.paas.pojo.dto.FormDataOwnerDTO;
import com.xbongbong.paas.pojo.dto.FormDataRepeatDTO;
import com.xbongbong.paas.pojo.dto.FormDataRestoreDTO;
import com.xbongbong.paas.pojo.dto.FormDataSubSummaryGetDTO;
import com.xbongbong.paas.pojo.dto.FormDataSummaryDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateGetDTO;
import com.xbongbong.paas.pojo.dto.FormRichTextBatchDTO;
import com.xbongbong.paas.pojo.dto.LinkConditionDataDTO;
import com.xbongbong.paas.pojo.dto.LinkFormDataDTO;
import com.xbongbong.paas.pojo.dto.LinkRelyDataDTO;
import com.xbongbong.paas.pojo.dto.LinkWorkOrderPhoneDTO;
import com.xbongbong.paas.pojo.dto.ParseSingleRowDataDTO;
import com.xbongbong.paas.pojo.dto.ProcessDataAddFormDataDTO;
import com.xbongbong.paas.pojo.dto.ProcessDataUpdateFormDataDTO;
import com.xbongbong.paas.pojo.dto.ProcessNodeTaskGetDTO;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.pojo.dto.StartProcessDTO;
import com.xbongbong.paas.pojo.dto.UserAndDepartmentGetDTO;
import com.xbongbong.paas.pojo.dto.ValidateDataDTO;
import com.xbongbong.paas.pojo.dto.WarehouseCheckDTO;
import com.xbongbong.paas.pojo.vo.AfterSaveVO;
import com.xbongbong.paas.pojo.vo.AggSumVO;
import com.xbongbong.paas.pojo.vo.ButtonGetVO;
import com.xbongbong.paas.pojo.vo.CheckRepeatVO;
import com.xbongbong.paas.pojo.vo.CustomerMergeVO;
import com.xbongbong.paas.pojo.vo.DeleteFormDataByBusinessRuleVO;
import com.xbongbong.paas.pojo.vo.DistributorAddressVo;
import com.xbongbong.paas.pojo.vo.DistributorReceiverVo;
import com.xbongbong.paas.pojo.vo.FormCountGetVO;
import com.xbongbong.paas.pojo.vo.FormDataAddGetVO;
import com.xbongbong.paas.pojo.vo.FormDataAddVO;
import com.xbongbong.paas.pojo.vo.FormDataDeleteVO;
import com.xbongbong.paas.pojo.vo.FormDataFastUpdateVO;
import com.xbongbong.paas.pojo.vo.FormDataGetVO;
import com.xbongbong.paas.pojo.vo.FormDataListVO;
import com.xbongbong.paas.pojo.vo.FormDataOwnerVO;
import com.xbongbong.paas.pojo.vo.FormDataRepeatVO;
import com.xbongbong.paas.pojo.vo.FormDataRestoreVO;
import com.xbongbong.paas.pojo.vo.FormDataSummaryVO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateGetVO;
import com.xbongbong.paas.pojo.vo.FormDataUpdateVO;
import com.xbongbong.paas.pojo.vo.LinkDataDefaultVO;
import com.xbongbong.paas.pojo.vo.LinkFormDataVO;
import com.xbongbong.paas.pojo.vo.LinkRelyDataVO;
import com.xbongbong.paas.pojo.vo.LinkRelyDataWorkOrderPhoneVO;
import com.xbongbong.paas.pojo.vo.LinkResultDataVO;
import com.xbongbong.paas.pojo.vo.PaasFormDataEsListVO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.pojo.vo.ProcessDataAddFormDataVO;
import com.xbongbong.paas.pojo.vo.ProcessDataUpdateFormDataVO;
import com.xbongbong.paas.pojo.vo.ProcessNodeTaskGetVO;
import com.xbongbong.paas.pojo.vo.SearchDataInConditionVO;
import com.xbongbong.paas.pojo.vo.StartProcessVO;
import com.xbongbong.paas.pojo.vo.UserAndDepartmentGetVO;
import com.xbongbong.paas.pojo.vo.UserFormPermissionVO;
import com.xbongbong.paas.pojo.workflow.task.dto.WorkflowNodeTaskGetDTO;
import com.xbongbong.paas.pojo.workflow.task.vo.WorkflowNodeTaskGetVO;
import com.xbongbong.paas.redis.RedisPrefixConstant;
import com.xbongbong.paas.service.CallCenterCommonService;
import com.xbongbong.paas.service.CompanyConfigService;
import com.xbongbong.paas.service.DistinctDataService;
import com.xbongbong.paas.service.MarketingManagementService;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.service.PaasFormDataService;
import com.xbongbong.paas.service.PaasFormExplainService;
import com.xbongbong.paas.service.PaasFormService;
import com.xbongbong.paas.service.ProLinkBusinessService;
import com.xbongbong.paas.service.ProModelService;
import com.xbongbong.paas.service.TemplateService;
import com.xbongbong.paas.service.UserService;
import com.xbongbong.paas.service.impl.base.BaseFormDataService;
import com.xbongbong.paas.service.team.TeamDataHelp;
import com.xbongbong.paas.service.workflow.WorkflowApproveListPageOperationService;
import com.xbongbong.paas.service.workflow.trigger.WorkflowFormDataOperationService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.pojo.PermissionTermsPojo;
import com.xbongbong.paas.toolbox.thread.TransmittableThreadLocalUtil;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.PageHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.BaseDTO;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.EsConditionUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.ItemUtil;
import com.xbongbong.paas.util.SearchConditionUtil;
import com.xbongbong.parent.condition.ProConditionHelp;
import com.xbongbong.parent.data.FormDataEsService;
import com.xbongbong.parent.explain.FormDataAddFormExplainHandlerName;
import com.xbongbong.parent.explain.FormDataDetailFormExplainHandleName;
import com.xbongbong.parent.explain.FormDataFormExplainHandleName;
import com.xbongbong.parent.explain.FormDataListFormExplainHandleName;
import com.xbongbong.parent.explain.FormDataUpdateGetExplainHandler;
import com.xbongbong.parent.interfaces.BusinessDetailBaseInfoService;
import com.xbongbong.parent.interfaces.BusinessDetailTopInfoService;
import com.xbongbong.parent.interfaces.BusinessEditPageRenderService;
import com.xbongbong.parent.interfaces.BusinessNewPageRenderService;
import com.xbongbong.parent.interfaces.FormDataService;
import com.xbongbong.parent.interfaces.FormDataUpdateService;
import com.xbongbong.parent.parse.data.FormDataGetAnalysisDataHelp;
import com.xbongbong.parent.parse.data.FormDataLinkDataGetServiceImpl;
import com.xbongbong.parent.parse.data.FormDataListAnalysisDataHelp;
import com.xbongbong.parent.parse.data.FormDataUpdateGetAnalysisDataHelp;
import com.xbongbong.parent.util.CommonBusinessFieldUtil;
import com.xbongbong.parent.util.SerialNoUtil;
import com.xbongbong.pro.appdetail.pojo.MobileDetailMoneyItemPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailSpecialInfoPojo;
import com.xbongbong.pro.appdetail.pojo.MobileDetailStatusBlockPojo;
import com.xbongbong.pro.businessdata.pojo.dto.BusinessDataDTO;
import com.xbongbong.pro.businessdata.pojo.dto.BussinessCustomerListRelyDTO;
import com.xbongbong.pro.businessdata.pojo.dto.DistributorAddressDTO;
import com.xbongbong.pro.businessdata.pojo.dto.DistributorReceiverDTO;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.businessdata.pojo.dto.ProductListDataDTO;
import com.xbongbong.pro.businessdata.pojo.vo.BusinessCustomerListRelyVO;
import com.xbongbong.pro.companyconfig.pojo.dto.CompanyConfigHasBeenEnableDTO;
import com.xbongbong.pro.companyconfig.pojo.vo.CompanyConfigHasBeenEnableVO;
import com.xbongbong.pro.condition.pojo.ConditionDTO;
import com.xbongbong.pro.constant.BusinessConstant;
import com.xbongbong.pro.constant.CommonConstant;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.constant.SymbolConstant;
import com.xbongbong.pro.custombutton.pojo.CustomButtonPojo;
import com.xbongbong.pro.custombutton.pojo.dto.CustomButtonListDTO;
import com.xbongbong.pro.custombutton.pojo.vo.CustomButtonListVO;
import com.xbongbong.pro.decisiontree.pojo.dto.ContactSearchListDTO;
import com.xbongbong.pro.defaultData.pojo.dto.DefaultDataDTO;
import com.xbongbong.pro.defaultData.pojo.vo.DefaultDataVO;
import com.xbongbong.pro.detailtab.dto.OrderOnPinDTO;
import com.xbongbong.pro.domain.entity.FormConfigEntity;
import com.xbongbong.pro.domain.entity.FormTeamSetEntity;
import com.xbongbong.pro.domain.entity.LabelEntity;
import com.xbongbong.pro.domain.entity.LinkProductRelyEntity;
import com.xbongbong.pro.domain.entity.PersonLabelEntity;
import com.xbongbong.pro.domain.entity.SearchCustomerCompanyEntity;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.AmountFlagEnum;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.PaasStageEnum;
import com.xbongbong.pro.enums.PackageStatusEnum;
import com.xbongbong.pro.enums.PackageTypeEnum;
import com.xbongbong.pro.enums.ReceiveStatusEnum;
import com.xbongbong.pro.enums.RefundStatusEnum;
import com.xbongbong.pro.enums.RelTypeEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.SoukeMealEnum;
import com.xbongbong.pro.enums.SummaryTypeEnum;
import com.xbongbong.pro.enums.ValueAddedTypeEnum;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ContactErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ContractErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.CustomerErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.PaymentErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.ProductErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.QuotationErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.RaidersErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.TemplateErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.WorkReportErrorCodeEnum;
import com.xbongbong.pro.enums.fund.enums.ModelTypeEnum;
import com.xbongbong.pro.enums.lowcode.ButtonTypeEnum;
import com.xbongbong.pro.enums.permission.enums.ProPermissionAliasEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormOwnerUniqueEnum;
import com.xbongbong.pro.enums.teammembers.enums.FormPatternEnum;
import com.xbongbong.pro.es.pojo.EsScriptConditionPojo;
import com.xbongbong.pro.es.pojo.EsScriptPojo;
import com.xbongbong.pro.form.pojo.TopPermissionsPoJo;
import com.xbongbong.pro.form.pojo.dto.EsDataDTO;
import com.xbongbong.pro.form.pojo.dto.FormConfigGetDTO;
import com.xbongbong.pro.formdata.pojo.AfterSavePojo;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formdata.pojo.SaasSpecialParamPojo;
import com.xbongbong.pro.formdata.pojo.dto.CheckDateDTO;
import com.xbongbong.pro.formdata.pojo.dto.DefaultOwnerAndCoUserGetDTO;
import com.xbongbong.pro.formdata.pojo.dto.FormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.dto.FormDataRepeatBatchDTO;
import com.xbongbong.pro.formdata.pojo.dto.InheritRuleDTO;
import com.xbongbong.pro.formdata.pojo.dto.MobileFormDataDetailDTO;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formdata.pojo.vo.BeforeSaveVO;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.CheckDateVO;
import com.xbongbong.pro.formdata.pojo.vo.DefaultOwnerAndCoUserGetVO;
import com.xbongbong.pro.formdata.pojo.vo.FormDataDetailVO;
import com.xbongbong.pro.formdata.pojo.vo.InheritRuleVO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormCommonDetailVO;
import com.xbongbong.pro.formdata.pojo.vo.MobileFormDataDetailVO;
import com.xbongbong.pro.formdata.pojo.vo.SaveVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.formexplain.pojo.ConditionExplainPojo;
import com.xbongbong.pro.formexplain.pojo.DefaultLinkInfoPojo;
import com.xbongbong.pro.formexplain.pojo.HandleExplainPojo;
import com.xbongbong.pro.formexplain.pojo.dto.HandlerExplainDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.pro.fundtransfer.pojo.dto.CheckTransferDateDTO;
import com.xbongbong.pro.fundtransfer.pojo.vo.CheckTransferDateVO;
import com.xbongbong.pro.invoice.pojo.InvoiceSpecialParamPojo;
import com.xbongbong.pro.invoice.pojo.dto.InvoiceAmountDetailDTO;
import com.xbongbong.pro.label.pojo.LabelPojo;
import com.xbongbong.pro.label.pojo.dto.PersonLabelFindDTO;
import com.xbongbong.pro.link.business.pojo.vo.LinkBusinessGetVO;
import com.xbongbong.pro.listbatch.pojo.dto.HandoverDTO;
import com.xbongbong.pro.lowcodeconfig.pojo.dto.LowCodeConfigGetDTO;
import com.xbongbong.pro.lowcodeconfig.pojo.vo.LowCodeConfigGetVO;
import com.xbongbong.pro.payment.pojo.dto.PaymentDTO;
import com.xbongbong.pro.payment.pojo.dto.PaymentWriteOffDTO;
import com.xbongbong.pro.payment.pojo.vo.PaymentWriteOffVO;
import com.xbongbong.pro.payplan.pojo.dto.PayPlanDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyAddPermissionDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyUpdatePermissionDTO;
import com.xbongbong.pro.permission.pojo.dto.VerifyViewPermissionDTO;
import com.xbongbong.pro.product.pojo.StockNotifyPojo;
import com.xbongbong.pro.product.pojo.dto.FilterAttrOnOffJXCDTO;
import com.xbongbong.pro.product.pojo.dto.PagingProductDTO;
import com.xbongbong.pro.product.pojo.vo.DetailProductVO;
import com.xbongbong.pro.product.pojo.vo.SourceProductListVO;
import com.xbongbong.pro.sheet.pojo.dto.SheetAmountDetailGetDTO;
import com.xbongbong.pro.sheet.pojo.vo.HandleLinkInfoVO;
import com.xbongbong.pro.sheet.pojo.vo.SheetAmountDetailGetVO;
import com.xbongbong.pro.team.TeamLinkPOJO;
import com.xbongbong.pro.template.pojo.EnablePojo;
import com.xbongbong.pro.template.pojo.dto.TemplateDTO;
import com.xbongbong.pro.thread.ThreadPoolBeanConfig;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojoExt;
import com.xbongbong.pro.warehouse.pojo.vo.WarehouseListVO;
import com.xbongbong.pro.weblist.pojo.RepeatFieldPojo;
import com.xbongbong.pro.weblist.pojo.RepeatInfo;
import com.xbongbong.pro.weblist.pojo.RepeatPojo;
import com.xbongbong.pro.weblist.pojo.dto.CustomerRepeatDTO;
import com.xbongbong.pro.weblist.pojo.dto.DataInfoDTO;
import com.xbongbong.pro.weblist.pojo.dto.RepeatToolFieldGetDTO;
import com.xbongbong.pro.weblist.pojo.vo.CustomerRepeatVO;
import com.xbongbong.pro.weblist.pojo.vo.DataInfoVO;
import com.xbongbong.pro.weblist.pojo.vo.RecheckRepeatVO;
import com.xbongbong.pro.weblist.pojo.vo.RepeatFieldListVO;
import com.xbongbong.pro.weblist.pojo.vo.WaitPurchaseConfiglVO;
import com.xbongbong.pro.weblist.pojo.vo.WaitPurchaseDetailVO;
import com.xbongbong.process.data.ProcessDataSynchronizedFormService;
import com.xbongbong.process.operate.ProcessStartHelp;
import com.xbongbong.saas.base.EnumBase;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.InvoiceConstant;
import com.xbongbong.saas.constant.MultiUnitConstant;
import com.xbongbong.saas.constant.PageConstant;
import com.xbongbong.saas.constant.ParameterConstant;
import com.xbongbong.saas.constant.ProductConstant;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.AssembleProductEntity;
import com.xbongbong.saas.domain.entity.BomProductEntity;
import com.xbongbong.saas.domain.entity.BusinessProductEntity;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.CostAdjustProductEntity;
import com.xbongbong.saas.domain.entity.CouponEntity;
import com.xbongbong.saas.domain.entity.CustomerSubDataEntity;
import com.xbongbong.saas.domain.entity.FundAccountEntity;
import com.xbongbong.saas.domain.entity.InstockProductEntity;
import com.xbongbong.saas.domain.entity.InventoryProductEntity;
import com.xbongbong.saas.domain.entity.KnowledgeBaseEntity;
import com.xbongbong.saas.domain.entity.OpportunityProductEntity;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.ProductCategoryEntity;
import com.xbongbong.saas.domain.entity.ProductStockEntity;
import com.xbongbong.saas.domain.entity.ProductWarehouseEntity;
import com.xbongbong.saas.domain.entity.ProductionOrderProductEntity;
import com.xbongbong.saas.domain.entity.PromotionProductEntity;
import com.xbongbong.saas.domain.entity.PurchaseProductEntity;
import com.xbongbong.saas.domain.entity.ReturnedPurchaseProductEntity;
import com.xbongbong.saas.domain.entity.StockFlowBillEntity;
import com.xbongbong.saas.domain.entity.SupplierProductEntity;
import com.xbongbong.saas.domain.entity.TransferProductEntity;
import com.xbongbong.saas.domain.entity.UserTeamEntity;
import com.xbongbong.saas.domain.entity.WarehouseOristockEntity;
import com.xbongbong.saas.domain.entity.WarehouseOristockProductEntity;
import com.xbongbong.saas.domain.entity.WarehouseSubDataEntity;
import com.xbongbong.saas.domain.entity.WarehouseUserEntity;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderExplainEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFlowNodeEntity;
import com.xbongbong.saas.domain.entity.WorkOrderProductEntity;
import com.xbongbong.saas.domain.entity.WorkOrderStageEntity;
import com.xbongbong.saas.domain.entity.WorkOrderTemplateEntity;
import com.xbongbong.saas.domain.entity.WorkPlanEntity;
import com.xbongbong.saas.domain.entity.ext.AssembleEntityExt;
import com.xbongbong.saas.domain.entity.ext.BomBillEntityExt;
import com.xbongbong.saas.domain.entity.ext.ClueEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContactEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.ContractSubDataExt;
import com.xbongbong.saas.domain.entity.ext.CostAdjustEntityExt;
import com.xbongbong.saas.domain.entity.ext.CreditLimitEntityExt;
import com.xbongbong.saas.domain.entity.ext.CustomerEntityExt;
import com.xbongbong.saas.domain.entity.ext.InstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.InventoryEntityExt;
import com.xbongbong.saas.domain.entity.ext.InvoiceEntityExt;
import com.xbongbong.saas.domain.entity.ext.MarketActivityEntityExt;
import com.xbongbong.saas.domain.entity.ext.OpportunityEntityExt;
import com.xbongbong.saas.domain.entity.ext.OutstockEntityExt;
import com.xbongbong.saas.domain.entity.ext.PayPlanEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentEntityExt;
import com.xbongbong.saas.domain.entity.ext.PaymentSheetEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductEntityExt;
import com.xbongbong.saas.domain.entity.ext.ProductionOrderEntityExt;
import com.xbongbong.saas.domain.entity.ext.PurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.QuotationEntityExt;
import com.xbongbong.saas.domain.entity.ext.RefundEntityExt;
import com.xbongbong.saas.domain.entity.ext.ReturnedPurchaseEntityExt;
import com.xbongbong.saas.domain.entity.ext.SupplierEntityExt;
import com.xbongbong.saas.domain.entity.ext.TransferEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderExplainEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.BusinessDetailTabEnum;
import com.xbongbong.saas.enums.BusinessFieldEnum;
import com.xbongbong.saas.enums.BusinessProductTableNameEnum;
import com.xbongbong.saas.enums.CompanyConfigEnum;
import com.xbongbong.saas.enums.CreditLimitStatusEnum;
import com.xbongbong.saas.enums.DetailTabEnum;
import com.xbongbong.saas.enums.DistributorAddressEnum;
import com.xbongbong.saas.enums.DistributorCreditStatusEnum;
import com.xbongbong.saas.enums.FormConfigEnum;
import com.xbongbong.saas.enums.GuaranteeStatusEnum;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.LinkProductRelyEnum;
import com.xbongbong.saas.enums.ListGroupEnum;
import com.xbongbong.saas.enums.ListOptionEnum;
import com.xbongbong.saas.enums.ListSearchEnum;
import com.xbongbong.saas.enums.ListTopButtonEnum;
import com.xbongbong.saas.enums.MobileDetailBottomOperationEnum;
import com.xbongbong.saas.enums.NumberTypeEnum;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperatePageEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OutLinkSettingTypeEnum;
import com.xbongbong.saas.enums.OuterLinkTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.PaasDetailTabEnum;
import com.xbongbong.saas.enums.PageTitleEnum;
import com.xbongbong.saas.enums.PhoneExtEnum;
import com.xbongbong.saas.enums.PlaceholderEnum;
import com.xbongbong.saas.enums.ProductPrintHelpEnum;
import com.xbongbong.saas.enums.RedundantTemplateTypeEnum;
import com.xbongbong.saas.enums.RepeatTypeEnum;
import com.xbongbong.saas.enums.RowNameEnum;
import com.xbongbong.saas.enums.SaasButtonEnum;
import com.xbongbong.saas.enums.SaasSpecialListEnum;
import com.xbongbong.saas.enums.SelectProductEnum;
import com.xbongbong.saas.enums.SheetAloneEnum;
import com.xbongbong.saas.enums.ShowTypeEnum;
import com.xbongbong.saas.enums.TagEnum;
import com.xbongbong.saas.enums.VisibleRangeEnum;
import com.xbongbong.saas.enums.WorkOrderStatusEnum;
import com.xbongbong.saas.enums.WorkOrderTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.base.ManagementBaseEnum;
import com.xbongbong.saas.enums.base.PaymentBaseEnum;
import com.xbongbong.saas.enums.base.PaymentSheetBaseEnum;
import com.xbongbong.saas.enums.business.AssembleEnum;
import com.xbongbong.saas.enums.business.BomBillEnum;
import com.xbongbong.saas.enums.business.ClueEnum;
import com.xbongbong.saas.enums.business.CommunicatePlanEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.ContactEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.ContractOutstockEnum;
import com.xbongbong.saas.enums.business.CostAdjustEnum;
import com.xbongbong.saas.enums.business.CreditLimitEnum;
import com.xbongbong.saas.enums.business.CustomerCommunicateEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.DistributorAccountEnum;
import com.xbongbong.saas.enums.business.DistributorEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.InventoryEnum;
import com.xbongbong.saas.enums.business.InvoiceEnum;
import com.xbongbong.saas.enums.business.OrderEnum;
import com.xbongbong.saas.enums.business.OtherExpenseEnum;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentBalanceEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.PaymentTaskEnum;
import com.xbongbong.saas.enums.business.PaymentWriteOffEnum;
import com.xbongbong.saas.enums.business.ProductEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.PurchaseInvoiceEnum;
import com.xbongbong.saas.enums.business.QuotationEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.business.ReturnEnum;
import com.xbongbong.saas.enums.business.ReturnedPurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierCommunicateEnum;
import com.xbongbong.saas.enums.business.SupplierContactEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.enums.business.TransferEnum;
import com.xbongbong.saas.enums.business.WaitInstockEnum;
import com.xbongbong.saas.enums.business.WaitOutstockEnum;
import com.xbongbong.saas.enums.business.WarehouseEnum;
import com.xbongbong.saas.enums.business.WorkOrderEnum;
import com.xbongbong.saas.enums.business.WorkOrderOutstockEnum;
import com.xbongbong.saas.enums.business.WorkReportDailyEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.enums.business.WorkReportPlanEnum;
import com.xbongbong.saas.enums.business.WorkReportTypeEnum;
import com.xbongbong.saas.enums.dictionary.AllOutBoundEnum;
import com.xbongbong.saas.enums.dictionary.ArchivedEnum;
import com.xbongbong.saas.enums.dictionary.ClueStatusEnum;
import com.xbongbong.saas.enums.dictionary.CommunicatePlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.InventoryStatusEnum;
import com.xbongbong.saas.enums.dictionary.IsCancelEnum;
import com.xbongbong.saas.enums.dictionary.OrderStatusEnum;
import com.xbongbong.saas.enums.dictionary.PayPlanStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentStatusEnum;
import com.xbongbong.saas.enums.dictionary.PaymentTaskStatusEnum;
import com.xbongbong.saas.enums.dictionary.ProductionOrderStatusEnum;
import com.xbongbong.saas.enums.dictionary.ReturnedStatusEnum;
import com.xbongbong.saas.enums.dictionary.ShipStatusEnum;
import com.xbongbong.saas.enums.dictionary.TransferStatusEnum;
import com.xbongbong.saas.enums.product.AssembleProductEnum;
import com.xbongbong.saas.enums.product.ContractProductEnum;
import com.xbongbong.saas.enums.product.CostAdjustProductEnum;
import com.xbongbong.saas.enums.product.InstockProductEnum;
import com.xbongbong.saas.enums.product.InventoryProductEnum;
import com.xbongbong.saas.enums.product.OutstockProductEnum;
import com.xbongbong.saas.enums.product.PriceSetScopeEnum;
import com.xbongbong.saas.enums.product.RefundProductEnum;
import com.xbongbong.saas.enums.product.TransferProductEnum;
import com.xbongbong.saas.enums.product.WorkOrderProductEnum;
import com.xbongbong.saas.enums.subform.ProductStockSubFormEnum;
import com.xbongbong.saas.enums.subform.ProductWarehouseSubFormEnum;
import com.xbongbong.saas.help.CompetitorHelp;
import com.xbongbong.saas.help.DecisionTreeHelp;
import com.xbongbong.saas.help.ExplainHelp;
import com.xbongbong.saas.help.FormDataAnalysisHelp;
import com.xbongbong.saas.help.FormatProductHelp;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.help.InvoiceCommonHelper;
import com.xbongbong.saas.help.LabelHelp;
import com.xbongbong.saas.help.MarketingHelp;
import com.xbongbong.saas.help.ProDetailHandlerHelp;
import com.xbongbong.saas.help.RelativeProductHelp;
import com.xbongbong.saas.help.SaasAddHelp;
import com.xbongbong.saas.help.SaasDataInitHelp;
import com.xbongbong.saas.help.SaasDetailPermissionHelp;
import com.xbongbong.saas.help.SaasFormHelp;
import com.xbongbong.saas.help.SaasGetHelp;
import com.xbongbong.saas.help.SaasHelp;
import com.xbongbong.saas.help.SaasListHelp;
import com.xbongbong.saas.help.SaasPayPlanHelper;
import com.xbongbong.saas.help.SaasPaymentHelper;
import com.xbongbong.saas.help.SaasSaveHelp;
import com.xbongbong.saas.help.SaasUpdateHelp;
import com.xbongbong.saas.help.ScoreRuleHelp;
import com.xbongbong.saas.help.StageHelp;
import com.xbongbong.saas.help.WorkOrderListDataPermissionHelp;
import com.xbongbong.saas.model.AssembleModel;
import com.xbongbong.saas.model.AssembleProductModel;
import com.xbongbong.saas.model.BomBillModel;
import com.xbongbong.saas.model.BomProductModel;
import com.xbongbong.saas.model.ClueModel;
import com.xbongbong.saas.model.CommunicatePlanUserModel;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContactUserModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.CostAdjustModel;
import com.xbongbong.saas.model.CostAdjustProductModel;
import com.xbongbong.saas.model.CouponModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.CustomerSubDataModel;
import com.xbongbong.saas.model.FormConfigModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.InstockModel;
import com.xbongbong.saas.model.InstockProductModel;
import com.xbongbong.saas.model.InventoryModel;
import com.xbongbong.saas.model.InventoryProductModel;
import com.xbongbong.saas.model.InvoiceModel;
import com.xbongbong.saas.model.KnowledgeBaseModel;
import com.xbongbong.saas.model.LabelModel;
import com.xbongbong.saas.model.LinkProductRelyModel;
import com.xbongbong.saas.model.MarketActivityModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.OpportunityProductModel;
import com.xbongbong.saas.model.OutstockModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PayPlanSheetModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.PaymentSheetModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductStockModel;
import com.xbongbong.saas.model.ProductUnitPriceModel;
import com.xbongbong.saas.model.ProductWarehouseModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.ProductionOrderProductModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.PurchaseProductModel;
import com.xbongbong.saas.model.QuotationModel;
import com.xbongbong.saas.model.QuotationProductModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.ReturnedPurchaseModel;
import com.xbongbong.saas.model.ReturnedPurchaseProductModel;
import com.xbongbong.saas.model.StockFlowBillModel;
import com.xbongbong.saas.model.SupplierContactModel;
import com.xbongbong.saas.model.SupplierContactUserModel;
import com.xbongbong.saas.model.SupplierModel;
import com.xbongbong.saas.model.SupplierProductModel;
import com.xbongbong.saas.model.TagLinkModel;
import com.xbongbong.saas.model.TransferModel;
import com.xbongbong.saas.model.TransferProductModel;
import com.xbongbong.saas.model.WarehouseOristockProductModel;
import com.xbongbong.saas.model.WarehouseSubDataModel;
import com.xbongbong.saas.model.WarehouseUserModel;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFlowNodeModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.saas.model.WorkOrderProductModel;
import com.xbongbong.saas.model.WorkOrderStageModel;
import com.xbongbong.saas.model.WorkOrderTemplateModel;
import com.xbongbong.saas.model.WorkReportModel;
import com.xbongbong.saas.model.impl.WarehouseOristockModelImpl;
import com.xbongbong.saas.service.ClueService;
import com.xbongbong.saas.service.ContractProductService;
import com.xbongbong.saas.service.CreditLimitService;
import com.xbongbong.saas.service.CustomerService;
import com.xbongbong.saas.service.DistributorFormDataService;
import com.xbongbong.saas.service.FundSetService;
import com.xbongbong.saas.service.InventoryService;
import com.xbongbong.saas.service.KnowledgeDataService;
import com.xbongbong.saas.service.MarketActivityService;
import com.xbongbong.saas.service.MobileDetailService;
import com.xbongbong.saas.service.PayBalanceService;
import com.xbongbong.saas.service.PayPlanService;
import com.xbongbong.saas.service.PayPlanSheetService;
import com.xbongbong.saas.service.PaymentBalanceService;
import com.xbongbong.saas.service.PaymentService;
import com.xbongbong.saas.service.PaymentSheetService;
import com.xbongbong.saas.service.PersonLabelService;
import com.xbongbong.saas.service.PriceSetService;
import com.xbongbong.saas.service.ProductCategoryService;
import com.xbongbong.saas.service.ProductService;
import com.xbongbong.saas.service.ProductStockInfoService;
import com.xbongbong.saas.service.PurchaseProductService;
import com.xbongbong.saas.service.QuotationService;
import com.xbongbong.saas.service.RecheckingRuleService;
import com.xbongbong.saas.service.SaasListService;
import com.xbongbong.saas.service.UserTeamService;
import com.xbongbong.saas.service.WarehouseService;
import com.xbongbong.saas.service.WorkOrderFormDataService;
import com.xbongbong.saas.service.impl.AssembleServiceImpl;
import com.xbongbong.saas.service.impl.BomBillServiceImpl;
import com.xbongbong.saas.service.impl.BusinessProductServiceImpl;
import com.xbongbong.saas.service.impl.ContractServiceImpl;
import com.xbongbong.saas.service.impl.InstockServiceImpl;
import com.xbongbong.saas.service.impl.OpportunityServiceImpl;
import com.xbongbong.saas.service.impl.OutstockServiceImpl;
import com.xbongbong.saas.service.impl.ProductionOrderServiceImpl;
import com.xbongbong.saas.service.impl.PurchaseServiceImpl;
import com.xbongbong.saas.service.impl.RefundServiceImpl;
import com.xbongbong.saas.service.impl.ReturnedPurchaseServiceImpl;
import com.xbongbong.saas.service.impl.TransferServiceImpl;
import com.xbongbong.saas.service.impl.WorkOrderServiceImpl;
import com.xbongbong.saas.service.toolbox.help.AttrDecimalPrecisionHelper;
import com.xbongbong.saas.service.toolbox.help.FundMoneyHelp;
import com.xbongbong.saas.service.toolbox.help.PackageStatusHelp;
import com.xbongbong.saas.service.toolbox.help.ProductHelp;
import com.xbongbong.saas.service.toolbox.help.SaasListDataPermissionHelp;
import com.xbongbong.saas.service.toolbox.help.UserTeamHelp;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.CompanyConfigEntity;
import com.xbongbong.sys.domain.entity.DepartmentEntity;
import com.xbongbong.sys.domain.entity.PriceProductSetEntity;
import com.xbongbong.sys.domain.entity.PriceSetEntity;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.help.ProPermissionHelp;
import com.xbongbong.sys.model.CompanyConfigModel;
import com.xbongbong.sys.model.DepartmentModel;
import com.xbongbong.sys.model.PriceSetModel;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.util.ContractCompareUtil;
import com.xbongbong.util.OwnerIdAndCoUserIdUtil;
import com.xbongbong.workorder.explain.WorkOrderFormDataFormExplainHandleName;
import com.xbongbong.workorder.service.WorkOrderBasicService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.join.query.HasParentQueryBuilder;
import org.elasticsearch.join.query.JoinQueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static com.xbongbong.paas.elasticsearch.constant.EsNormalConstant.MINI_MUM_SHOULD_MATCH;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getIntegerOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.existsQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.rangeQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author: wufeng
 * @date: 2018/8/27 20:14
 * @desrcption:
 */
@Service
public class PaasFormDataServiceImpl extends BaseFormDataService implements PaasFormDataService {

    private static final Logger LOG = LoggerFactory.getLogger(PaasFormDataServiceImpl.class);

    @Resource
    private DistinctDataService distinctDataService;
    @Resource
    private ExplainHelp explainHelp;
    @Resource
    private UserService userService;
    @Resource
    private FormDataListFormExplainHandleName formDataListFormExplainHandleName;
    @Resource
    private FormDataFormExplainHandleName formDataFormExplainHandleName;
    @Resource
    private FormDataAddFormExplainHandlerName formDataAddFormExplainHandlerName;
    @Resource
    private PaasMenuModel paasMenuModel;
    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private PaasFormDataEsModel paasFormDataEsModel;
    @Resource
    private PaasProcessTemplateModel paasProcessTemplateModel;
    @Resource
    private MongoLogHelp mongoLogHelp;
    @Resource
    private FormDataLinkDataGetServiceImpl formDataLinkDataGetServiceImpl;
    @Resource
    private FormDataLinkDataUpdateGetServiceImpl formDataLinkDataUpdateGetService;
    @Resource
    private EsHelper esHelper;
    @Resource
    private FormDataListAnalysisDataHelp formDataListAnalysisDataHelp;
    @Resource
    private FormDataGetAnalysisDataHelp formDataGetAnalysisDataHelp;
    @Resource
    private FormDataDetailFormExplainHandleName formDataDetailFormExplainHandleName;
    @Resource
    private FormDataUpdateGetAnalysisDataHelp formDataUpdateGetAnalysisDataHelp;
    @Resource
    private UserHelp userHelp;
    @Resource
    private ProModelService proModelService;
    @Resource
    private SaasSaveHelp saasSaveHelp;
    @Resource
    private SaasUpdateHelp saasUpdateHelp;
    @Resource
    private FormExplainHelp formExplainHelp;
    @Resource
    private SaasListHelp saasListHelp;
    @Resource
    private SaasHelp saasHelp;
    @Resource
    private ProGetHelp proGetHelp;
    @Resource
    private SaasAddHelp saasAddHelp;
    @Resource
    private SaasGetHelp saasGetHelp;
    @Resource
    private PayPlanSheetService payPlanSheetService;

    @Resource
    private Map<Integer, BusinessEditPageRenderService> businessEditPageRenderMap;
    @Resource
    private ContactModel contactModel;
    @Resource
    private SupplierContactModel supplierContactModel;
    @Resource
    private ProductService productService;
    @Resource
    private PaymentService paymentService;
    @Resource
    private PayPlanService payPlanService;
    @Resource
    private MobileDetailService mobileDetailService;
    @Resource
    private PaasFormExplainService paasFormExplainService;
    @Resource
    private PaymentSheetService paymentSheetService;
    @Resource
    private PaymentSheetModel paymentSheetModel;
    @Resource
    private PayPlanSheetModel payPlanSheetModel;
    @Resource
    private WorkOrderFormDataService workOrderFormDataService;
    @Resource
    private CommunicatePlanUserModel communicatePlanUserModel;
    @Resource
    private UserTeamService userTeamService;
    @Resource
    private UserModel userModel;
    @Resource
    private ProcessStartHelp processStartHelp;
    @Resource
    private RefundServiceImpl refundService;
    @Resource
    private WorkOrderFlowNodeModel workOrderFlowNodeModel;
    @Resource
    private WorkOrderTemplateModel workOrderTemplateModel;
    @Resource
    private WorkOrderStageModel workOrderStageModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private WorkOrderFormDataFormExplainHandleName workOrderFormDataFormExplainHandleName;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private SaasListDataPermissionHelp saasListDataPermissionHelp;
    @Resource
    private SaasDetailPermissionHelp saasDetailPermissionHelp;
    @Resource
    private CommonPermissionHelp commonPermissionHelp;
    @Resource
    private ProPermissionHelp proPermissionHelp;
    @Resource
    private WorkOrderBasicService workOrderBasicService;
    @Resource
    private WorkOrderListDataPermissionHelp workOrderListDataPermissionHelp;
    @Resource
    private Map<Integer, BusinessNewPageRenderService> businessNewPageRenderMap;
    @Resource
    private FormDataListSearchHelp formDataListSearchHelp;
    @Resource
    private PaasFormHelp paasFormHelp;
    @Resource
    private TemplateService templateService;
    @Resource
    private AttrDecimalPrecisionHelper attrDecimalPrecisionHelper;
    @Resource
    private CallCenterCommonService callCenterCommonService;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private ProductCategoryService productCategoryService;
    @Resource
    private PackageStatusHelp packageStatusHelp;
    @Resource
    private PackageHelp packageHelp;
    @Resource
    private ProDetailHandlerHelp proDetailHandlerHelp;
    @Resource
    private PaasAppService paasAppService;
    @Resource
    private SearchCustomerCompanyModel searchCustomerCompanyModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private ProductStockInfoService productStockInfoService;
    @Resource
    private WarehouseService warehouseService;
    @Resource
    private QuotationService quotationService;
    @Resource
    private OpportunityServiceImpl opportunityService;
    @Resource
    private PaasProcessDataModel paasProcessDataModel;
    @Resource
    private PaymentBalanceService paymentBalanceService;
    @Resource
    private ProLinkBusinessService proLinkBusinessService;
    @Resource
    private BaseLinkBoolQueryBuilderService baseLinkBoolQueryBuilderService;
    @Resource
    private ProFormHelp proFormHelp;
    @Resource
    private ProConditionHelp proConditionHelp;
    @Resource
    private PaasFormService paasFormService;
    @Resource
    private FormConfigModel formConfigModel;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private ProductModel productModel;
    @Resource
    private PayBalanceService payBalanceService;
    @Resource
    private InvoiceCommonHelper invoiceCommonHelper;
    @Resource
    private FundMoneyHelp fundMoneyHelp;
    @Resource
    private FormDataValidateProductHelp formDataValidateProductHelp;
    @Resource
    private CompanyConfigService companyConfigService;
    @Resource
    private SupplierProductModel supplierProductModel;
    @Resource
    private RelativeProductHelp relativeProductHelp;
    @Resource
    private SaasFormHelp saasFormHelp;
    @Resource
    private InventoryService inventoryService;
    @Resource
    private WarehouseUserModel warehouseUserModel;
    @Resource
    private WorkReportModel workReportModel;
    @Resource
    private InventoryProductModel inventoryProductModel;
    @Resource
    private PurchaseProductModel purchaseProductModel;
    @Resource
    private TransferProductModel transferProductModel;
    @Resource
    private AssembleProductModel assembleProductModel;
    @Resource
    private WorkOrderProductModel workOrderProductModel;
    @Resource
    private ReturnedPurchaseProductModel returnedPurchaseProductModel;
    @Resource
    private BomProductModel bomProductModel;
    @Resource
    private ProductionOrderProductModel productionOrderProductModel;
    @Resource
    private InstockProductModel instockProductModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private LinkProductRelyModel linkProductRelyModel;
    @Resource
    private BusinessProductServiceImpl businessProductService;
    @Resource
    private ProductStockModel productStockModel;
    @Resource
    private QuotationModel quotationModel;
    @Resource
    private InventoryModel inventoryModel;
    @Resource
    private OutstockModel outstockModel;
    @Resource
    private InstockModel instockModel;
    @Resource
    private TransferModel transferModel;
    @Resource
    private AssembleModel assembleModel;
    @Resource
    private WorkOrderModel workorderModel;
    @Resource
    private ReturnedPurchaseModel returnedPurchaseModel;
    @Resource
    private BomBillModel bomBillModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private OpportunityProductModel opportunityProductModel;
    @Resource
    private PaasProcessNodeTaskServiceImpl paasProcessNodeTaskService;
    @Resource
    private InstockServiceImpl instockService;
    @Resource
    private OutstockServiceImpl outstockService;
    @Resource
    private ProductionOrderServiceImpl productionOrderService;
    @Resource
    private TransferServiceImpl transferService;
    @Resource
    private BomBillServiceImpl bomBillService;
    @Resource
    private PurchaseServiceImpl purchaseService;
    @Resource
    private ReturnedPurchaseServiceImpl returnedPurchaseService;
    @Resource
    private ProductWarehouseModel productWarehouseModel;
    @Resource
    private AssembleServiceImpl assembleService;
    @Resource
    private ContractServiceImpl contractService;
    @Resource
    private WorkOrderServiceImpl workOrderService;
    @Resource
    private QuotationProductModel quotationProductModel;
    @Resource
    private RefundModel refundModel;
    @Resource
    private FundSetService fundSetService;
    @Resource
    private DepartmentModel departmentModel;
    @Resource
    private PaasFormDataService paasFormDataService;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private SaasListService saasListService;
    @Resource
    private PaasProcessRelatedDataModel paasProcessRelatedDataModel;
    @Resource
    private TagLinkModel tagLinkModel;
    @Resource
    private OuterLinkModel outerLinkModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private TransferSubFormHelper transferSubFormHelper;
    @Resource
    private FormatProductHelp formatProductHelp;
    @Resource
    private CloudCodeHelp cloudCodeHelp;
    @Resource
    private ProductUnitPriceModel productUnitPriceModel;
    @Resource
    private PaasOuterLinkConfigService outerLinkConfigService;
    @Resource
    private FormDataServiceFactory formDataServiceFactory;
    @Resource
    private DistributorFormDataService distributorFormDataService;
    @Resource
    private PriceSetService priceSetService;
    @Resource
    private MarketingManagementService marketingManagementService;
    @Resource
    private CustomerSubDataModel customerSubDataModel;
    @Resource
    private CreditLimitService creditLimitService;
    @Resource
    private LabelModel labelModel;
    @Resource
    private ScoreRuleHelp scoreRuleHelp;
    @Resource
    private CustomerService customerService;
    @Resource
    private MarketActivityService marketActivityService;
    @Resource
    private ClueService clueService;
    @Resource
    private LabelHelp labelHelp;
    @Resource
    private LowCodeConfigService lowCodeConfigService;
    @Resource
    private CustomButtonService customButtonService;
    @Resource
    private UserTeamHelp userTeamHelp;
    @Resource
    private WorkflowFormDataOperationService workflowFormDataOperationService;
    @Resource
    private RepeatHelp repeatHelp;
    @Resource
    private FormDataAnalysisHelp formDataAnalysisHelp;
    @Resource
    private WorkflowApproveListPageOperationService workflowApproveListPageOperationService;

    @Resource
    private ProductHelp productHelp;
    @Resource
    private MarketingHelp marketingHelp;
    @Resource
    private WarehouseSubDataModel warehouseSubDataModel;
    @Resource
    private CouponModel couponModel;
    @Resource
    private CompanyConfigModel companyConfigModel;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private ThreadPoolBeanConfig threadPoolBeanConfig;
    @Resource
    private SaasPaymentHelper saasPaymentHelper;
    @Resource
    private SaasPayPlanHelper saasPayPlanHelper;
    @Resource
    private PaasDataFormDataUpdateServiceImpl paasDataFormDataUpdateService;
    @Resource
    private PurchaseProductService purchaseProductService;
    @Resource
    private ContractProductService contractProductService;
    @Resource
    private PaasFormSubDataEsModel paasFormSubDataEsModel;
    @Resource
    private PersonLabelService personLabelService;
    @Resource
    private RichTextService richTextService;
    @Resource
    private InvoiceModel invoiceModel;
    @Resource
    private CostAdjustModel costAdjustModel;
    @Resource
    private FormDataEsService formDataService;
    @Autowired
    private Map<Integer, BusinessDetailTopInfoService> businessDetailTopInfoMap;
    @Autowired
    private Map<Integer, BusinessDetailBaseInfoService> businessDetailBasicInfoMap;
    @Resource
    private SerialNoService serialNoService;
    @Resource
    private FineClueHelp fineClueHelp;
    @Resource
    private ProcessDataSynchronizedFormService processDataSynchronizedFormService;
    @Resource
    private FormDataUpdateServiceFactory formDataUpdateServiceFactory;
    @Resource
    private PhoneHelp phoneHelp;
    @Resource
    private Map<Integer, AbstractFineClueService> fineClueServiceMap;
    @Resource
    private DecisionTreeHelp decisionTreeHelp;
    @Resource
    private IndexTypeModel indexTypeModel;
    @Resource
    private TeamDataHelp teamDataHelp;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private MarketActivityModel marketActivityModel;
    @Resource
    private ClueModel clueModel;
    @Resource
    private FormTeamSetHelp formTeamSetHelp;
    @Resource
    private ContactUserModel contactUserModel;
    @Resource
    private SupplierContactUserModel supplierContactUserModel;
    @Resource
    private StockFlowBillModel stockFlowBillModel;
    @Resource
    private CostAdjustProductModel costAdjustProductModel;
    @Resource
    private WarehouseOristockModelImpl warehouseOristockModel;
    @Resource
    private WarehouseOristockProductModel warehouseOristockProductModel;
    @Resource
    private KnowledgeBaseModel knowledgeBaseModel;
    @Resource
    private KnowledgeDataService knowledgeDataService;

    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private StageHelp stageHelp;
    @Resource
    private PriceSetModel priceSetModel;
    @Resource
    private DistributorProModelServiceImpl distributorProModelService;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;
    @Resource
    private FormDataActiveRuleHelp formDataActiveRuleHelp;
    @Resource
    private CompetitorHelp competitorHelp;

    @Resource
    private FormDataUpdateGetExplainHandler formDataUpdateGetExplainHandler;
    @Resource
    private ContractCompareUtil contractCompareUtil;
    @Resource
    private RecheckingRuleService recheckingRuleService;
    @Resource
    private PaasAppModel paasAppModel;

    @Override
    public FormDataListVO list(FormDataListDTO formDataListDTO) throws XbbException {
        FormDataListVO formDataListVO = new FormDataListVO();
        try {
            Map<String, Object> map = BeanUtil.convertBean2Map(formDataListDTO, true);
            PageHelper pageHelper = PageHelperUtil.getPageHelper(map, paasFormDataModel, formDataListDTO.getPageSize());

            StringBuffer stringBuffer = SearchConditionUtil.sqlStringBuffer(formDataListDTO);

            map.put("condition", stringBuffer.toString());
            List<PaasFormDataEntityExt> list = (List<PaasFormDataEntityExt>) PageHelperUtil.getEntityList(map, pageHelper, paasFormDataModel);
            if ( list == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            List<PaasFormExplainEntity> paasFormExplainEntity = paasFormExplainModel.list(map);
            if ( paasFormExplainEntity == null || paasFormExplainEntity.isEmpty() ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            formDataListVO.setHeadList(JSONArray.parseArray(paasFormExplainEntity.get(0).getExplains(), FieldAttrEntity.class));
            formDataListVO.setFormDataList(list);
            formDataListVO.setPageHelper(pageHelper);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataListVO;
    }

    @Override
    public PaasFormDataEsListVO listByEs(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO formDataListVO;
        try {
            formDataListVO = formDataListSearchHelp.getEsList(formDataListDTO);
            boolean notExport = Objects.isNull(formDataListDTO.getFromExport()) || Objects.equals(0, formDataListDTO.getFromExport());
            if ( !notExport) {
                return formDataListVO;
            }
            if ( PlatFormEnum.WEB.getValue().equals(formDataListDTO.getPlatform()) ) {
                //设置阶段预警颜色部分数据
                formDataListSearchHelp.setWarningColorData(formDataListDTO, formDataListVO);
                formDataListSearchHelp.webDataAnalysis(formDataListDTO, formDataListVO);
            } else if ( PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform()) ) {
                formDataListVO = formDataListSearchHelp.appDataAnalysis(formDataListDTO, formDataListVO);
            }
            /* ==================== 上部按钮权限和下部按钮权限 ==================== */
            formDataListSearchHelp.setButtons(formDataListDTO, formDataListVO);
            //表单冻结和隐藏列设置（在按钮设置后处理，防止操作列无法冻结和隐藏）
            formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, formDataListVO);
            if (Objects.equals(formDataListVO.getUpdateTime(), formDataListDTO.getUpdateTime())) {
                formDataListVO.setHeadList(new ArrayList<>());
            }
        } catch (XbbException e) {
            LOG.error("错误信息" , e);
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataListVO;
    }

    @Override
    public PaasFormDataEsListVO listByCloudCode(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO formDataListVO;
        try {
            formDataListVO = formDataListSearchHelp.getEsList(formDataListDTO);
            formDataListSearchHelp.cloudCodeDataAnalysis(formDataListDTO, formDataListVO);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataListVO;
    }

    @Override
    public FormDataSummaryVO getFormDataSummary(FormDataSummaryDTO formDataSummaryDTO) throws XbbException {
        FormDataSummaryVO formDataSummaryVO = new FormDataSummaryVO();
        Integer businessType = formDataSummaryDTO.getBusinessType();
        FormDataListDTO dataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(formDataSummaryDTO, dataListDTO);
        // 处理范围筛选
        saasListHelp.commonFilter(dataListDTO);
        formDataSummaryDTO.setConditions(dataListDTO.getConditions());
        if ( Objects.equals(SaasMarkEnum.SAAS.getCode(), formDataSummaryDTO.getSaasMark()) ) {
            List<ConditionsEntityExt> conditionList = formDataSummaryDTO.getConditions();
            if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.WAREHOUSE.getCode())) {
                if (Objects.equals(formDataSummaryDTO.getSubBusinessType(), XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
                    Long groupId = formDataSummaryDTO.getListGroupId() == null ? ListGroupEnum.PRODUCT_SEARCH.getCode() : formDataSummaryDTO.getListGroupId();
                    ListGroupEnum listGroupEnum = ListGroupEnum.getByCode(groupId.intValue());
                    if (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.STOCK_SEARCH.getCode()) || Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.WARNING_SEARCH.getCode())) {
                        return getStockSearchSummary(dataListDTO);
                    } else if (Objects.equals(listGroupEnum.getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                        return getGuaranteeSearchSummary(dataListDTO);
                    }
                }
                saasListDataPermissionHelp.listDepAndUserDataPermission(formDataSummaryDTO.getShouldConditions(), formDataSummaryDTO.getLoginUser(), businessType, formDataSummaryDTO.getLoginUser().getDepSet());
//                fix bug20977  如果是查询产品汇总需要考虑是否计算子产品
                if ( Objects.equals(formDataSummaryDTO.getSubBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) ) {
                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(ProductEnum.PARENT_ID.getAttr(), "", ProductEnum.PARENT_ID.getFieldType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(0));
                    conditionList.add(conditionsEntityExt);
                    formDataSummaryDTO.setConditions(conditionList);
                }
            } else if (Objects.equals(businessType,XbbRefTypeEnum.INVOICE.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                formDataSummaryDTO.setStatusFilter(saasListHelp.invoiceSetStatusFilterHandle(formDataSummaryDTO.getListGroupId()));
                saasListDataPermissionHelp.listDataPermission(conditionList, formDataSummaryDTO.getLoginUser(), businessType,formDataSummaryDTO.getSubBusinessType());
                formDataSummaryDTO.setConditions(conditionList);
            } else if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
                if (Objects.equals(formDataSummaryDTO.getSubBusinessType(), XbbRefTypeEnum.WORK_ORDER_ROB.getCode())) {
                    ConditionsEntityExt  conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(FieldTypeEnum.WORK_ORDER_ROB.getAlias());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ROB.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(WorkOrderTypeEnum.ROB.getCode()));
                    formDataSummaryDTO.getConditions().add(conditionsEntityExt);
                    workOrderListDataPermissionHelp.robListDataPermission(formDataSummaryDTO.getConditions(), formDataSummaryDTO.getLoginUser(), formDataSummaryDTO.getLoginUser().getDepSet());
                } else {
                    ConditionsEntityExt  conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(FieldTypeEnum.WORK_ORDER_ROB.getAlias());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ROB.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(WorkOrderTypeEnum.NORMAL.getCode()));
                    formDataSummaryDTO.getConditions().add(conditionsEntityExt);
                    workOrderListDataPermissionHelp.listDataPermission(formDataSummaryDTO.getConditions(),formDataSummaryDTO.getShouldConditions(), formDataSummaryDTO.getLoginUser(),formDataSummaryDTO.getDefaultGroup(),formDataSummaryDTO.getListGroupId());
                }
            } else {
                List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, formDataSummaryDTO.getLoginUser(), businessType, formDataSummaryDTO.getSubBusinessType());
                // 共享权限处理
                ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataSummaryDTO.getFormId()), formDataSummaryDTO.getLoginUser());
                formDataSummaryDTO.setSharePermission(sharePermission);
            }
        } else {
            List<ConditionsEntityExt> permissionConditions = formDataListSearchHelp.getPaasPermission(dataListDTO);
            // 共享权限处理
            ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(formDataSummaryDTO.getFormId()), formDataSummaryDTO.getLoginUser());
            formDataSummaryDTO.setSharePermission(sharePermission);
        }
        if ( !Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(), businessType) && !Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(), businessType)) {
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(FieldTypeEnum.FLOW_STATUS.getAlias(), "", FieldTypeEnum.FLOW_STATUS.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType()));
            formDataSummaryDTO.getConditions().add(conditionsEntityExt);
        }
        try {
            FormDataListDTO formDataListDTO = new FormDataListDTO();
            BeanUtil.copyProperties(formDataSummaryDTO, formDataListDTO);
            List<ConditionsEntityExt> groupConditionsList = new ArrayList<>();
            List<List<ConditionsEntityExt>> shouldCondition = new ArrayList<>();
            saasListHelp.packageGroupList(formDataListDTO, groupConditionsList, shouldCondition);
            formDataSummaryDTO.getConditions().addAll(groupConditionsList);
            formDataSummaryDTO.getShouldConditions().addAll(shouldCondition);
            saasListHelp.selectProductCondition(formDataListDTO.getConditions(),formDataListDTO.getCorpid());
            List<ConditionsEntityExt> subConditionsList = saasListHelp.packageConditionBySubBusinessType(formDataSummaryDTO.getSubBusinessType(), formDataSummaryDTO.getCorpid(), formDataSummaryDTO.getUserId(), formDataSummaryDTO.getStatusFilter());
            formDataSummaryDTO.getConditions().addAll(subConditionsList);
            Long formId = formDataSummaryDTO.getFormId();
            String corpid = formDataSummaryDTO.getCorpid();
            PaasFormEntityExt form = new PaasFormEntityExt();
            if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                //工单
                WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, corpid);
                BeanUtil.copyProperties(workOrderFormEntityExt, form);
            } else {
                form = paasFormModel.getByKey(formId, corpid);
            }
            if ( form == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
            if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(formId, corpid);
                BeanUtil.copyProperties(workOrderExplainEntityExt, paasFormExplainEntity);
            } else {
                paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            }
            if ( paasFormExplainEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
            explainList.forEach(item -> {
                explainMap.put(item.getAttr(), item);
            });
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataSummaryDTO, handlerExplainDTO, false);
            handlerExplainDTO.setExplainList(explainList);
            handlerExplainDTO.setPaasFormEntityExt(form);
            HandlerExplainVO handlerExplainVO = formDataListFormExplainHandleName.handleExplain(handlerExplainDTO);
            if ( handlerExplainVO == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            explainList = handlerExplainVO.getHeadList();
            boolean isInvoice = Objects.equals(formDataSummaryDTO.getBusinessType(),XbbRefTypeEnum.INVOICE.getCode()) || Objects.equals(formDataSummaryDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
            String totalMoneyAttr = InvoiceEnum.TOTAL_MONEY.getAttr();
            String cancelAttr = InvoiceEnum.IS_CANCEL.getAttr();
            if(Objects.equals(formDataSummaryDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                totalMoneyAttr = PurchaseInvoiceEnum.TOTAL_MONEY.getAttr();
                cancelAttr = PurchaseInvoiceEnum.IS_CANCEL.getAttr();
            }
            if(isInvoice && Objects.equals(formDataSummaryDTO.getListGroupId(), 0L)) {
                //除去作废
                List<ConditionsEntityExt> conditionsEntityExts = formDataSummaryDTO.getConditions();
                if (CollectionsUtil.isEmpty(conditionsEntityExts)) {
                    conditionsEntityExts = new ArrayList<>();
                }
                ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                conditionsEntityExt.setAttr(cancelAttr);
                conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
                conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                conditionsEntityExt.setValue(Collections.singletonList(BasicConstant.ZERO));
                conditionsEntityExts.add(conditionsEntityExt);
                formDataSummaryDTO.setConditions(conditionsEntityExts);
            }
            // 汇总数字类型的字段的全部数据，并返回列表
            List<AggSumVO> numCountList = getNumCount(explainList, formDataSummaryDTO);
            if ( Objects.isNull(numCountList) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            JSONObject jsonObject = new JSONObject();
            if(isInvoice && Objects.equals(formDataSummaryDTO.getListGroupId(), 0L)){
                //发票 需要展示作废的金额,需要再查一次
                List<FieldAttrEntity> canelTotalMoneyList = new ArrayList<>();
                if (explainMap.containsKey(totalMoneyAttr)) {
                    canelTotalMoneyList.add(explainMap.get(totalMoneyAttr));
                }
                for(ConditionsEntityExt conditionsEntityExt : formDataSummaryDTO.getConditions()){
                    if(Objects.equals(conditionsEntityExt.getAttr(),InvoiceEnum.IS_CANCEL.getAttr()) && Objects.equals(formDataSummaryDTO.getBusinessType(),XbbRefTypeEnum.INVOICE.getCode())){
                        conditionsEntityExt.setAttr(cancelAttr);
                        conditionsEntityExt.setValue(Collections.singletonList(BasicConstant.ONE));
                    }else if (Objects.equals(conditionsEntityExt.getAttr(),PurchaseInvoiceEnum.IS_CANCEL.getAttr()) && Objects.equals(formDataSummaryDTO.getBusinessType(),XbbRefTypeEnum.PURCHASE_INVOICE.getCode())) {
                        conditionsEntityExt.setAttr(cancelAttr);
                        conditionsEntityExt.setValue(Collections.singletonList(BasicConstant.ONE));
                    }
                }
                List<AggSumVO> cancelCountList = getNumCount(canelTotalMoneyList, formDataSummaryDTO);
                for ( AggSumVO aggSumVO : numCountList ) {
                    jsonObject.put(aggSumVO.getAttr(), aggSumVO.getValue());
                    if ( Objects.equals(aggSumVO.getAttr(),totalMoneyAttr) ) {
                        if ( CollectionsUtil.isNotEmpty(cancelCountList) ) {
                            JSONObject valueJson = new JSONObject();
                            valueJson.put("value", aggSumVO.getValue());
                            valueJson.put("cancelValue", cancelCountList.get(0).getValue());
                            jsonObject.put(aggSumVO.getAttr(), valueJson);
                        }
                    }
                }
                formDataSummaryVO.setSummary(jsonObject);
            } else if ( Objects.equals(formDataSummaryDTO.getBusinessType(), XbbRefTypeEnum.PAYMENT_SHEET.getCode()) ) {
                sheetSummary(explainMap, formDataSummaryDTO, numCountList, formDataSummaryVO, XbbRefTypeEnum.PAYMENT_SHEET);
            } else if (Objects.equals(formDataSummaryDTO.getBusinessType(), XbbRefTypeEnum.PAY_SHEET.getCode())) {
                sheetSummary(explainMap, formDataSummaryDTO, numCountList, formDataSummaryVO, XbbRefTypeEnum.PAY_SHEET);
            } else {
                numCountList.forEach(item -> {
                    if (Objects.nonNull(item.getAttr())) {
                        jsonObject.put(item.getAttr(), item.getValue());
                    }
                });
                formDataSummaryVO.setSummary(jsonObject);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("formData.getFormDataSummary数据汇总出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataSummaryVO;
    }

    private FormDataSummaryVO getGuaranteeSearchSummary(FormDataListDTO formDataListDTO) throws XbbException {
        FormDataSummaryVO formDataSummaryVO = new FormDataSummaryVO();
        formDataListDTO.setFromExport(1);
        formDataListDTO.setPageSize(10000);
        formDataListDTO.setPage(1);
        String corpid = formDataListDTO.getCorpid();

        // 筛选
        List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
        ConditionsEntityExt productCondition = null;
        ConditionsEntityExt warehouseCondition = null;
        ConditionsEntityExt batchCondition = null;
        for (ConditionsEntityExt condition : conditions) {
            if (Objects.equals(ProductEnum.NAME.getAttr(), condition.getAttr())) {
                productCondition = condition;
            } else if (Objects.equals(SelectProductEnum.WAREHOUSE.getSaasAttr(), condition.getAttr())) {
                warehouseCondition = condition;
            } else if (Objects.equals(SelectProductEnum.BATCH.getSaasAttr(), condition.getAttr())) {
                batchCondition = condition;
            }
        }
        // 公司配置：是否显示0库存
        CompanyConfigHasBeenEnableDTO companyConfigHasBeenEnableDTO = new CompanyConfigHasBeenEnableDTO(CompanyConfigEnum.ZERO_STOCK.getAlias());
        BeanUtil.copyProperties(formDataListDTO,companyConfigHasBeenEnableDTO);
        CompanyConfigHasBeenEnableVO companyConfigHasBeenEnableVO = companyConfigService.hasBeenEnable(companyConfigHasBeenEnableDTO);
        if (Objects.equals(companyConfigHasBeenEnableVO.getEnable(),1)) {

        }

        // 产品信息
        List<Long> productIdList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID, formDataListDTO.getCorpid()));
        boolQueryBuilder.mustNot(termQuery(ProductEnum.getEsAttr4Keyword(ProductEnum.PARENT_ID), 0));
        if (Objects.nonNull(productCondition)) {
            boolQueryBuilder.filter(termsQuery(BusinessConstant.ID, productCondition.getValue()));
        }
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        searchSourceBuilder.query(boolQueryBuilder);
        List<PaasFormDataEntityExt> productList = paasEsModel.list(searchSourceBuilder, IndexTypeEnum.IDX_SAAS_PRODUCT, null, formDataListDTO.getPage(), formDataListDTO.getPageSize());
        productList.forEach(item -> productIdList.add(item.getDataId()));

        // 批次库存
        boolQueryBuilder = boolQuery();
        searchSourceBuilder = new SearchSourceBuilder();
        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(ParameterConstant.CORPID, formDataListDTO.getCorpid()));
        boolQueryBuilder.filter(termsQuery(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.PRODUCT_ID), productIdList));
        if (Objects.nonNull(warehouseCondition)) {
            boolQueryBuilder.filter(termsQuery(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.WAREHOUSE_ID), warehouseCondition.getValue()));
        }
        if (Objects.nonNull(batchCondition)) {
            boolQueryBuilder.filter(termsQuery(ProductStockSubFormEnum.getEsAttr(ProductStockSubFormEnum.BATCH), batchCondition.getValue()));
        }
        // 分组
        GuaranteeStatusEnum guaranteeStatusEnum;
        ConditionsEntityExt conditionsEntityExt = null;
        if (Objects.equals(formDataListDTO.getListGroupId().intValue(), ListGroupEnum.GUARANTEE_SEARCH_EXPIRED.getCode())) {
            guaranteeStatusEnum = GuaranteeStatusEnum.OUT_OF_DATE;
            conditionsEntityExt = new ConditionsEntityExt(SelectProductEnum.EXPIRE_DATE.getSaasAttr(), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.RANGE.getSymbol(), Arrays.asList(guaranteeStatusEnum.getTime(), DateTimeUtil.getInt() + guaranteeStatusEnum.getTime()));
        } else if (Objects.equals(formDataListDTO.getListGroupId().intValue(), ListGroupEnum.GUARANTEE_SEARCH_EXPIRED_15.getCode())) {
            guaranteeStatusEnum = GuaranteeStatusEnum.EXPIRE_IN_FIFTEEN;
            conditionsEntityExt = new ConditionsEntityExt(SelectProductEnum.EXPIRE_DATE.getSaasAttr(), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.RANGE.getSymbol(), Arrays.asList(DateTimeUtil.getInt(), guaranteeStatusEnum.getTime() + DateTimeUtil.getInt()));
        } else if (Objects.equals(formDataListDTO.getListGroupId().intValue(), ListGroupEnum.GUARANTEE_SEARCH_EXPIRED_30.getCode())) {
            guaranteeStatusEnum = GuaranteeStatusEnum.EXPIRE_IN_THIRTY;
            conditionsEntityExt = new ConditionsEntityExt(SelectProductEnum.EXPIRE_DATE.getSaasAttr(), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.RANGE.getSymbol(), Arrays.asList(DateTimeUtil.getInt(), guaranteeStatusEnum.getTime() + DateTimeUtil.getInt()));
        } else if (Objects.equals(formDataListDTO.getListGroupId().intValue(), ListGroupEnum.GUARANTEE_SEARCH_EXPIRED_60.getCode())) {
            guaranteeStatusEnum = GuaranteeStatusEnum.EXPIRE_OVER_SIXTY;
            conditionsEntityExt = new ConditionsEntityExt(SelectProductEnum.EXPIRE_DATE.getSaasAttr(), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.RANGE.getSymbol(), Arrays.asList(DateTimeUtil.getInt(), guaranteeStatusEnum.getTime() + DateTimeUtil.getInt()));
        } else if (Objects.equals(formDataListDTO.getListGroupId().intValue(), ListGroupEnum.GUARANTEE_SEARCH_EXPIRED_60_MORE.getCode())) {
            guaranteeStatusEnum = GuaranteeStatusEnum.EXPIRE_OVER_SIXTY;
            conditionsEntityExt = new ConditionsEntityExt(SelectProductEnum.EXPIRE_DATE.getSaasAttr(), "", FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), ConditionEnum.GREATERTHAN.getSymbol(), Collections.singletonList(guaranteeStatusEnum.getTime()));
        }
        if (Objects.nonNull(conditionsEntityExt)) {
            EsUtil.conditionGuarantee(boolQueryBuilder, conditionsEntityExt.getSymbol(), conditionsEntityExt.getValue());
        }
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT_STOCK_INFO.getType()));
        searchSourceBuilder.query(boolQueryBuilder);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT_STOCK_INFO.getIndex());
        searchRequest.source(searchSourceBuilder);
        PageRequest pageRequest = EsUtil.setPage(searchSourceBuilder, formDataListDTO.getPage(), formDataListDTO.getPageSize());
        XbbAggregatedPage<PaasFormDataEntity> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntity.class);
        if (esEntities == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        List<ProductStockEntity> productStockEntities = transferSubFormHelper.transferFormDataToProductStockList(esEntities.getContent());

        Double totalCost = 0D;
        Double totalStock = 0D;
        for (ProductStockEntity productStockEntity : productStockEntities) {
            totalCost = Arith.add(totalCost, productStockEntity.getTotalCost() == null ? 0 : productStockEntity.getTotalCost());
            totalStock = Arith.add(totalStock, productStockEntity.getNum() == null ? 0 : productStockEntity.getNum());
        }

        PaasFormExplainEntity paasFormExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplain.getExplains(), null);
        // fix:32153,过滤产品成本汇总查看权限
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO);
        Boolean costIsHide = ExplainUtil.invisibleOfScope(explainMap.get(ProductEnum.COST.getAttr()), handlerExplainDTO);
        JSONObject summary = new JSONObject();
        if (costIsHide) {
            summary.put(SelectProductEnum.COST.getSaasAttr(), BasicConstant.NULL_SHOW_STR);
            summary.put(SelectProductEnum.TOTAL_COST.getSaasAttr(), BasicConstant.NULL_SHOW_STR);
        } else {
            double averageCost = 0D;
            Integer costAccuracy = explainMap.get(ProductEnum.COST.getAttr()).getAccuracy() == null ? 4 : explainMap.get(ProductEnum.COST.getAttr()).getAccuracy();
            if (totalStock != 0D) {
                averageCost = Arith.div(totalCost, totalStock, costAccuracy);
            }
            summary.put(SelectProductEnum.COST.getSaasAttr(),  AttrDecimalPrecisionHelper.parseThousandth(averageCost, costAccuracy));
            summary.put(SelectProductEnum.TOTAL_COST.getSaasAttr(),  AttrDecimalPrecisionHelper.parseThousandth(totalCost, costAccuracy));
        }

        boolean integerOnly = false;
        FieldAttrEntity stockField = explainMap.get(ProductEnum.STOCK.getAttr());
        if (stockField != null) {
            integerOnly = Objects.equals(stockField.getIntegerOnly(), 1);
        }
        if (Objects.equals(ListGroupEnum.getByCode(formDataListDTO.getListGroupId().intValue()).getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
            summary.put(SelectProductEnum.STOCK.getSaasAttr(), AttrDecimalPrecisionHelper.parseThousandth(totalStock, integerOnly ? 0 : explainMap.get(ProductEnum.STOCK.getAttr()).getAccuracy()));
        } else {
            summary.put(ProductEnum.STOCK.getAttr(), AttrDecimalPrecisionHelper.parseThousandth(totalStock, integerOnly ? 0 : explainMap.get(ProductEnum.STOCK.getAttr()).getAccuracy()));
        }
        formDataSummaryVO.setSummary(summary);
        return formDataSummaryVO;
    }


    /**
     * 子表单内的数据字段汇总 包括关联产品和普通子表单
     * @param
     * @return
     * @throws XbbException
     */
    @Override
    public FormDataSummaryVO getFormDataSubSummary(FormDataSubSummaryGetDTO formDataSubSummaryGetDTO) throws XbbException {
        FormDataSummaryVO formDataSummaryVO = new FormDataSummaryVO();
        UserEntity userEntity = new UserEntity();
        String attr = formDataSubSummaryGetDTO.getAttr();
        BeanUtil.copyProperties(formDataSubSummaryGetDTO.getLoginUser(), userEntity);
        Integer businessType = formDataSubSummaryGetDTO.getBusinessType();
        Integer linkBusinessType = formDataSubSummaryGetDTO.getLinkBusinessType();
        Long formId = formDataSubSummaryGetDTO.getFormId();
        String corpid = formDataSubSummaryGetDTO.getCorpid();
        //处理一下客户的业务类型并且是客户电话的字段就过滤掉这个汇总
        //客户对账单也不需要汇总（表格内已经把汇总信息计算过）
        boolean noSummary = (Objects.equals(linkBusinessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && Objects.equals(attr, CustomerManagementEnum.PHONE.getAttr())) || businessType.equals(XbbRefTypeEnum.CUSTOMER_STATEMENT.getCode());
        if (noSummary) {
            formDataSummaryVO.setSummary(new JSONObject());
             return formDataSummaryVO;
        }
        PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
        if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
            if (Objects.equals(formId, 0L)) {
                WorkOrderEntity workOrderEntity = workorderModel.getByKey(formDataSubSummaryGetDTO.getDataId(), corpid);
                formId = workOrderEntity.getFormId();
            }
            WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(formId, corpid);
            BeanUtil.copyProperties(workOrderExplainEntityExt, paasFormExplainEntity);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
            paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        } else if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER_V2.getCode()) && Objects.equals(0L, formId)) {
            PaasFormDataEntityExt paasFormDataEntityExt = paasEsModel.getByKey(formDataSubSummaryGetDTO.getDataId(), corpid, IndexTypeEnum.IDX_WORK_ORDER_V2, null);
            paasFormExplainEntity = paasFormExplainModel.getByFormId(paasFormDataEntityExt.getFormId(), corpid);
        } else {
            paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
        }
        if ( paasFormExplainEntity == null ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        FieldAttrEntity fieldAttrEntity = null;
        for (FieldAttrEntity item : explainList) {
            if (Objects.equals(item.getAttr(),attr)){
                fieldAttrEntity = item;
            }
        }
        // 本表单找不到该字段
        if(Objects.isNull(fieldAttrEntity)){
            formDataSummaryVO.setSummary(new JSONObject());
            return formDataSummaryVO;
        }
        // 关联其它表单的子表单暂时不支持该子表单的汇总
        if(Objects.nonNull(linkBusinessType)){
            formDataSummaryVO.setSummary(new JSONObject());
            return formDataSummaryVO;
        }
        // 汇总数字类型的字段的全部数据，并返回列表
        List<AggSumVO> numCountList = getSubNumCount(fieldAttrEntity, formDataSubSummaryGetDTO);
        if ( Objects.isNull(numCountList) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        JSONObject jsonObject = new JSONObject();
        numCountList.forEach(item -> {
            if (Objects.nonNull(item.getAttr())) {
                jsonObject.put(item.getAttr(), item.getValue());
            }
        });
        formDataSummaryVO.setSummary(jsonObject);
        return formDataSummaryVO;
    }

    @Override
    public FormDataSummaryVO getFormDataPrintSubSummary(ApprovePrintSubSummaryGetDTO approvePrintSubSummaryGetDTO) throws XbbException {
        FormDataSubSummaryGetDTO formDataSubSummaryGetDTO = new FormDataSubSummaryGetDTO();
        BeanUtil.copyProperties(approvePrintSubSummaryGetDTO,formDataSubSummaryGetDTO);
        formDataSubSummaryGetDTO.setAttr(approvePrintSubSummaryGetDTO.getAttr());
        FormDataSummaryVO formDataSummaryVO = getFormDataSubSummary(formDataSubSummaryGetDTO);
        JSONObject jsonObject = formDataSummaryVO.getSummary();
        if (Objects.equals(approvePrintSubSummaryGetDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue()) && jsonObject.containsKey(SelectProductEnum.BUSINESS_NUM.getAttr())) {
            jsonObject.put(SelectProductEnum.NUM.getAttr(), jsonObject.get(SelectProductEnum.BUSINESS_NUM.getAttr()));
        }
        return formDataSummaryVO;
    }

    private FormDataSummaryVO getStockSearchSummary(FormDataListDTO formDataListDTO) throws XbbException {
        FormDataSummaryVO formDataSummaryVO = new FormDataSummaryVO();
        formDataListDTO.setFromExport(1);
        formDataListDTO.setPageSize(10000);
        formDataListDTO.setPage(1);
        //formDataListDTO.setFieldList(Collections.singletonList(FieldTypeEnum.DATAID.getAlias()));
        String corpid = formDataListDTO.getCorpid();
        // 分类
        Long categoryId = 0L;
        // 仓库
        List<Long> selectWarehouseIdList = new ArrayList<>();
        formDataListDTO.setSelectWarehouseIdList(selectWarehouseIdList);
        // 筛选条件集合
        List<Long> warehouseIdList = selectWarehouseIdList;
        List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
        List<ConditionsEntityExt> productSearchConditions = new ArrayList<>();
        List<List<ConditionsEntityExt>> shouldConditions = formDataListDTO.getShouldConditions();
        Iterator<ConditionsEntityExt> iterator = conditionsEntityExtList.iterator();
        boolean hasWarehouseFilter = false;
        List<Long> supplierIdList = new ArrayList<>();
        while (iterator.hasNext()) {
            ConditionsEntityExt conditionsEntity = iterator.next();
            if (Objects.equals(ProductEnum.WAREHOUSE.getAttr(), conditionsEntity.getAttr())) {
                List<Object> selectValues = conditionsEntity.getValue();
                selectValues.forEach(item -> selectWarehouseIdList.add(Long.valueOf(item.toString())));
                hasWarehouseFilter = true;
            } else if (Objects.equals(ProductEnum.CATEGORY_ID.getAttr(), conditionsEntity.getAttr())) {
                List<Object> selectValues = conditionsEntity.getValue();
                for (Object selectValue : selectValues) {
                    categoryId = Long.valueOf(selectValue.toString());
                }
                iterator.remove();
            } else if (Objects.equals(conditionsEntity.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                conditionsEntity.setAttr(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
            } else if (Objects.equals(conditionsEntity.getAttr(),ProductEnum.SUPPLIER.getAttr())) {
                List<Object> selectValues = conditionsEntity.getValue();
                selectValues.forEach(item -> supplierIdList.add(Long.valueOf(item.toString())));
                iterator.remove();
            }
        }
        // 仓库权限 + 筛选
        List<Long> allWarehouseIdList = warehouseService.getWarehouseIdsByPermission(formDataListDTO.getLoginUser(),formDataListDTO.getLoginUser().getDepSet());
        if (!hasWarehouseFilter) {
            if (!formDataListDTO.getLoginUser().isMaxDataPermission()){
                warehouseIdList = allWarehouseIdList;
                // 低权限展开的仓库限定
                formDataListDTO.setSelectWarehouseIdList(warehouseIdList);
                if (allWarehouseIdList.isEmpty()){
                    allWarehouseIdList.add(-1L);
                }
                conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.WAREHOUSE.getAttr(),"",ProductEnum.WAREHOUSE.getFieldType(),ConditionEnum.INCLUDE.getSymbol(),new ArrayList<>(warehouseIdList)));
            } else {
                conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.WAREHOUSE.getAttr(),"",ProductEnum.WAREHOUSE.getFieldType(),ConditionEnum.NOEMPTY.getSymbol(),new ArrayList<>()));
            }
        } else {
            allWarehouseIdList.retainAll(warehouseIdList);
        }
        // 公司配置：是否显示0库存
        CompanyConfigHasBeenEnableDTO companyConfigHasBeenEnableDTO = new CompanyConfigHasBeenEnableDTO(CompanyConfigEnum.ZERO_STOCK.getAlias());
        BeanUtil.copyProperties(formDataListDTO,companyConfigHasBeenEnableDTO);
        CompanyConfigHasBeenEnableVO companyConfigHasBeenEnableVO = companyConfigService.hasBeenEnable(companyConfigHasBeenEnableDTO);
        if (Objects.equals(companyConfigHasBeenEnableVO.getEnable(),1)) {
            conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.STOCK.getAttr(), "", ProductEnum.STOCK.getFieldType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(0)));
            //productSearchConditions.add(new ConditionsEntityExt("num", "", FieldTypeEnum.NUM.getType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(0)));
        }
        // 供应商筛选
        if (!supplierIdList.isEmpty()) {
            List<SupplierProductEntity> supplierProductEntities = supplierProductModel.getSupplierProductBySupplierIdIn(corpid, supplierIdList);
            Set<Long> productIdIn = new HashSet<>();
            supplierProductEntities.forEach(item -> productIdIn.add(item.getProductId()));
            conditionsEntityExtList.add(new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(),"",FieldTypeEnum.DATAID.getType(),ConditionEnum.IN.getSymbol(),new ArrayList<>(productIdIn)));
        }
        // 分类筛选
        if (categoryId > 0) {
            List<Long> categoryIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<ProductCategoryEntity> productCategoryList = productCategoryService.getSubCategoryIdList(corpid, categoryId);
            productCategoryList.forEach((item)-> categoryIdIn.add(item.getId()));
            if (!categoryIdIn.isEmpty()) {
                conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.CATEGORY_ID.getAttr(),"",ProductEnum.CATEGORY_ID.getFieldType(),ConditionEnum.IN.getSymbol(),new ArrayList<>(categoryIdIn)));
            }
        }

        saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditions,formDataListDTO.getLoginUser(), XbbRefTypeEnum.PRODUCT.getCode(), formDataListDTO.getLoginUser().getDepSet());
        conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.PARENT_ID.getAttr(),"",ProductEnum.PARENT_ID.getFieldType(),ConditionEnum.NOEQUAL.getSymbol(),Collections.singletonList(0)));

        formDataListDTO.setProductSerchConditions(productSearchConditions);

        BoolQueryBuilder parentBoolQueryBuilder = boolQuery();
        parentBoolQueryBuilder.filter(termQuery("corpid.keyword",formDataListDTO.getCorpid()));
        parentBoolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        //parentBoolQueryBuilder.mustNot(termQuery(ProductEnum.getEsAttr4Keyword(ProductEnum.PARENT_ID),0));

        EsUtil.parseCondition(parentBoolQueryBuilder,formDataListDTO.getConditions(),"",formDataListDTO.getCorpid(),XbbRefTypeEnum.PRODUCT.getCode());
        EsUtil.setProductNameLike(formDataListDTO.getNameLike(),null,parentBoolQueryBuilder,true);
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",formDataListDTO.getCorpid()));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
        boolQueryBuilder.mustNot(termQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_ID), 0));
        boolQueryBuilder.filter(termQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_CHECKED),1));
        boolQueryBuilder.must(existsQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.NUM)));
        boolQueryBuilder.must(existsQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.COST)));
        if (!formDataListDTO.getSelectWarehouseIdList().isEmpty()) {
            //解析查询条件
            boolQueryBuilder.filter(termsQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_ID), formDataListDTO.getSelectWarehouseIdList()));
        }
        // 解析或条件
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        EsUtil.parseShouldCondition(parentBoolQueryBuilder,formDataListDTO.getShouldConditions(),formDataListDTO.getRel(),formDataListDTO.getCorpid(),formDataListDTO.getBusinessType());
        // 解析库存查询条件
        EsUtil.parseProductSearchCondition(boolQueryBuilder,formDataListDTO.getProductSerchConditions(),formDataListDTO.getRel(),formDataListDTO.getCorpid(),formDataListDTO.getSubBusinessType());
        HasParentQueryBuilder hasParentQueryBuilder = JoinQueryBuilders.hasParentQuery(IndexTypeEnum.IDX_SAAS_PRODUCT.getType(), parentBoolQueryBuilder, false);
        boolQueryBuilder.filter(hasParentQueryBuilder);
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCT_WAREHOUSE.getType()));
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
        List<AggSumDTO> summaryAttrList = new ArrayList<>();
        summaryAttrList.add(new AggSumDTO(ProductWarehouseSubFormEnum.COST.getDataAttr(), "cost", ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.COST)));
        summaryAttrList.add(new AggSumDTO(ProductWarehouseSubFormEnum.NUM.getDataAttr(), "num", ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.NUM)));
        List<AggSumVO> aggSumList = esHelper.aggStockSumByField(IndexTypeEnum.IDX_SAAS_PRODUCT_WAREHOUSE.getIndex(), summaryAttrList, searchQuery);
        Double totalCost = 0D;
        Double totalStock = 0D;
        for (AggSumVO item : aggSumList) {
            if (Objects.equals(item.getAttr(), ProductWarehouseSubFormEnum.COST.getDataAttr())) {
                totalCost = Arith.add(totalCost, Double.valueOf(item.getValue().toString()));
            } else if (Objects.equals(item.getAttr(), ProductWarehouseSubFormEnum.NUM.getDataAttr())) {
                totalStock = Arith.add(totalStock, Double.valueOf(item.getValue().toString()));
            }
        }
        /*PaasFormDataEsListVO formDataEsListVO = listByEs(formDataListDTO);
        List<PaasFormDataEntityExt> list = formDataEsListVO.getPaasFormDataESList();
        List<Long> dataIdList = new ArrayList<>();
        for (PaasFormDataEntityExt entity : list) {
            dataIdList.add(entity.getId());
        }
        dataIdList.add(-1L);
        PaasFormExplainEntity paasFormExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplain.getExplains(), null);
        Map<Long,JSONArray> productWarehouseMap = productListHelp.productWarehouseList(formDataListDTO, list, dataIdList, corpid, warehouseIdList, explainMap);
        double totalCost = 0D;
        double totalStock = 0D;
        for (Map.Entry<Long, JSONArray> entry : productWarehouseMap.entrySet()) {
            JSONArray jsonArray = entry.getValue();
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                if (!Objects.equals(jsonObject.get("costTotal"), BasicConstant.NULL_SHOW_STR)) {
                    totalCost = Arith.add(totalCost, jsonObject.getDouble("costTotal"));
                }
                if (!Objects.equals(jsonObject.get("stock"), BasicConstant.NULL_SHOW_STR)) {
                    totalStock = Arith.add(totalStock, jsonObject.getDouble("stock"));
                }
            }
        }*/
        PaasFormExplainEntity paasFormExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplain.getExplains(), null);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO);
        boolean costInvisible = ExplainUtil.invisibleOfScope(explainMap.get(ProductEnum.COST.getAttr()), handlerExplainDTO);
        boolean stockInvisible = ExplainUtil.invisibleOfScope(explainMap.get(ProductEnum.STOCK.getAttr()), handlerExplainDTO);
        JSONObject summary = new JSONObject();
        if (!costInvisible) {
            double averageCost = 0D;
            Integer costAccuracy = explainMap.get(ProductEnum.COST.getAttr()).getAccuracy() == null ? 4 : explainMap.get(ProductEnum.COST.getAttr()).getAccuracy();
            if (totalStock != 0D) {
                averageCost = Arith.div(totalCost, totalStock, costAccuracy);
            }
            summary.put("totalCost",  AttrDecimalPrecisionHelper.parseThousandth(totalCost, costAccuracy));
            if (Objects.nonNull(formDataListDTO.getListGroupId()) && Objects.nonNull(ListGroupEnum.getByCode(formDataListDTO.getListGroupId().intValue())) && Objects.equals(ListGroupEnum.getByCode(formDataListDTO.getListGroupId().intValue()).getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                summary.put(SelectProductEnum.COST.getSaasAttr(),  AttrDecimalPrecisionHelper.parseThousandth(averageCost, costAccuracy));
            } else {
                summary.put(ProductEnum.COST.getAttr(),  AttrDecimalPrecisionHelper.parseThousandth(averageCost, costAccuracy));
            }
        } else {
            summary.put("totalCost", BasicConstant.NULL_SHOW_STR);
            summary.put(ProductEnum.COST.getAttr(), BasicConstant.NULL_SHOW_STR);
        }
        if (!stockInvisible) {
            boolean integerOnly = false;
            FieldAttrEntity stockField = explainMap.get(ProductEnum.STOCK.getAttr());
            if (stockField != null) {
                integerOnly = Objects.equals(stockField.getIntegerOnly(), 1);
            }
            if (Objects.equals(ListGroupEnum.getByCode(formDataListDTO.getListGroupId().intValue()).getRefType(), XbbRefTypeEnum.GUARANTEE_SEARCH.getCode())) {
                summary.put(SelectProductEnum.STOCK.getSaasAttr(), AttrDecimalPrecisionHelper.parseThousandth(totalStock, integerOnly ? 0 : explainMap.get(ProductEnum.STOCK.getAttr()).getAccuracy()));
            } else {
                summary.put(ProductEnum.STOCK.getAttr(), AttrDecimalPrecisionHelper.parseThousandth(totalStock, integerOnly ? 0 : explainMap.get(ProductEnum.STOCK.getAttr()).getAccuracy()));
            }
        } else {
            summary.put(ProductEnum.STOCK.getAttr(), BasicConstant.NULL_SHOW_STR);
        }
        formDataSummaryVO.setSummary(summary);
        return formDataSummaryVO;
    }

    /**
     * 获取分组中的条件
     *
     * @param conditionList
     * @param listGroupConditionList
     */
    public void getConditionListByListGroupId(List<ConditionsEntityExt> conditionList, List<ConditionsEntityExt> listGroupConditionList) {
        if ( listGroupConditionList != null && !listGroupConditionList.isEmpty() ) {
            listGroupConditionList.forEach((item) -> {
                conditionList.add(item);
            });
        }
    }

    /**
     * 汇总数字字段
     *
     * @param explainList
     * @param formDataSummaryDTO
     * @return
     * @throws XbbException
     */
    public List<AggSumVO> getNumCount(List<FieldAttrEntity> explainList, FormDataSummaryDTO formDataSummaryDTO) throws XbbException {
        List<AggSumVO> numCountList = new ArrayList<>();
        Set<String> noPermissionSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        try {
            List<AggSumDTO> sumList = new ArrayList<>();
            List<AggSumDTO> avgList = new ArrayList<>();
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
            for ( FieldAttrEntity item : explainList ) {
                explainMap.put(item.getAttr(), item);
                // 不是数字类型的，不进行汇总
                if ( !item.getFieldType().equals(FieldTypeEnum.NUM.getType()) ) {
                    continue;
                }
                if ( !hasSumPermission(item, formDataSummaryDTO.getLoginUser()) ) {
                    noPermissionSet.add(item.getAttr());
                }

                if ( !Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), formDataSummaryDTO.getBusinessType())
                        && (Objects.isNull(item.getSummaryFlag()) || Objects.equals(item.getSummaryFlag(), SummaryTypeEnum.NONE.getType()))) {
                    continue;
                }
                AggSumDTO aggSumDTO = new AggSumDTO();
                aggSumDTO.setAttr(item.getAttr());
                aggSumDTO.setName(item.getAttrName());
                String field = item.getAttr();
                //预收款余额不在data里
                if ( !Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(), formDataSummaryDTO.getBusinessType()) && !Objects.equals(XbbRefTypeEnum.PREPAY_BALANCE.getCode(), formDataSummaryDTO.getBusinessType())) {
                    field = "data." + field;
                }
                aggSumDTO.setField(field);
                aggSumDTO.setFieldAttrEntity(item);

                if ( Objects.equals(item.getNumberType(), NumberTypeEnum.RATE.getCode()) ) {
                    avgList.add(aggSumDTO);
                    continue;
                }
                // 累加字段
                sumList.add(aggSumDTO);
                if ( Objects.equals(item.getSummaryFlag(), SummaryTypeEnum.AVERAGE.getType()) ) {
                    // 求平均字段
                    avgList.add(aggSumDTO);
                }
            }
            if ( Objects.equals(formDataSummaryDTO.getBusinessType(),XbbRefTypeEnum.PAYMENT.getCode()) ) {
                List<List<ConditionsEntityExt>> shoudConditions = formDataSummaryDTO.getShouldConditions();
                List<ConditionsEntityExt> conditions = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                ConditionsEntityExt conditionEqualOne = new ConditionsEntityExt(PaymentEnum.IS_RED.getAttr(), "", FieldTypeEnum.NUM.getType(), ConditionEnum.NOLIKE.getSymbol(), Arrays.asList(1));
                conditions.add(conditionEqualOne);
                shoudConditions.add(conditions);
            }
            // 地址查询条件封装
            FormDataListDTO formDataListDTO = new FormDataListDTO();
            formDataListDTO.setConditions(formDataSummaryDTO.getConditions());
            formDataListDTO.setShouldConditions(formDataSummaryDTO.getShouldConditions());
            saasListHelp.addressSearchShouldCondition(formDataListDTO);
            saasListHelp.addressSearchCondition(formDataListDTO);
            formDataSummaryDTO.setConditions(formDataListDTO.getConditions());
            formDataSummaryDTO.setShouldConditions(formDataListDTO.getShouldConditions());

            NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(formDataSummaryDTO.getCorpid(), formDataSummaryDTO.getBusinessType(), formDataSummaryDTO.getSaasMark());
            EsUtil.parseCondition(boolQueryBuilder, formDataSummaryDTO.getConditions(), formDataSummaryDTO.getRel(), formDataSummaryDTO.getCorpid(), formDataSummaryDTO.getBusinessType());
            EsUtil.parseShouldCondition(boolQueryBuilder, formDataSummaryDTO.getShouldConditions(), formDataSummaryDTO.getRel(), formDataSummaryDTO.getCorpid(), formDataSummaryDTO.getBusinessType());
            // 共享权限处理
            EsUtil.parseSharePermissionCondition(boolQueryBuilder, formDataSummaryDTO.getSharePermission(), formDataSummaryDTO.getCorpid(), formDataSummaryDTO.getBusinessType(), formDataListDTO.getFromThrough());
            if(Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(),formDataSummaryDTO.getBusinessType())){
                String nameLike = formDataSummaryDTO.getNameLike();
                if(StringUtil.isNotEmpty(nameLike)){
                    BoolQueryBuilder customerBoolQueryBuilder = boolQuery();
                    //解析查询条件
                    customerBoolQueryBuilder.filter(termQuery("corpid.keyword", formDataSummaryDTO.getCorpid()));
                    customerBoolQueryBuilder.filter(termQuery("del", 0));
                    customerBoolQueryBuilder.should(matchPhraseQuery(CustomerManagementEnum.getAttrConnectData(CustomerManagementEnum.NAME), nameLike));
                    customerBoolQueryBuilder.should(matchPhraseQuery(CustomerManagementEnum.getAttrConnectData(CustomerManagementEnum.PHONE)+".text_2", nameLike));
                    customerBoolQueryBuilder.minimumShouldMatch(EsNormalConstant.MINI_MUM_SHOULD_MATCH);
                    IndexTypeEnum customerIndex = indexTypeModel.getCustomerIndex(formDataSummaryDTO.getCorpid(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());

                    customerBoolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, customerIndex.getType()));
                    SearchRequest customerSearchRequest = new SearchRequest(customerIndex.getIndex());
                    SearchSourceBuilder customerSourceBuilder = new SearchSourceBuilder();
                    List<String> fieldList = Arrays.asList("id");
                    EsUtil.setFieldList(customerSourceBuilder, fieldList);
                    //模糊关联查询最多1W
                    PageRequest customerPageRequest =  EsUtil.setPage(customerSourceBuilder, 1,  SizeConstant.PAGE_SIZE);
                    customerSourceBuilder.query(customerBoolQueryBuilder);
                    customerSearchRequest.source(customerSourceBuilder);
                    XbbAggregatedPage<CustomerEntityExt> customerEntityExts =  xbbElasticsearchRestTemplate.queryForPages(customerPageRequest, customerSearchRequest,CustomerEntityExt.class);
                    if (customerEntityExts != null) {
                        List<CustomerEntityExt> customerResultList  = customerEntityExts.getContent();
                        List<Long> customerIdList = new ArrayList<>(customerResultList.size());
                        for (CustomerEntityExt customerEntityExt : customerResultList) {
                            customerIdList.add(customerEntityExt.getDataId());
                        }
                        boolQueryBuilder.filter(termsQuery(PaymentBalanceEnum.CUSTOMER_ID.getAttr(),customerIdList));
                    }
                }
            }else{
                EsUtil.setNameLike(formDataSummaryDTO.getSaasMark(), formDataSummaryDTO.getNameLike(), formDataSummaryDTO.getBusinessType(), false, boolQueryBuilder, formDataSummaryDTO.getShouldConditions().isEmpty(), explainMap, null);
            }
            // 拼接appId，菜单id等数据
            EsUtil.getTermQuery(boolQueryBuilder, formDataSummaryDTO, true);
            nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
            NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();

            if ( !sumList.isEmpty() ) {
                List<AggSumVO> aggSumList = esHelper.aggSumByField(indexTypeEnum.getIndex(), indexTypeEnum.getType(), sumList, searchQuery);
                for ( AggSumVO aggSumVO : aggSumList ) {
                    FieldAttrEntity fieldAttrEntity = explainMap.get(aggSumVO.getAttr());
                    Integer accuracy = Objects.equals(1, fieldAttrEntity.getIntegerOnly()) || fieldAttrEntity.getAccuracy() == null ? 0 : fieldAttrEntity.getAccuracy();
                    Object value = aggSumVO.getValue();
                    String valueStr = String.valueOf(value);
                    BigDecimal bigDecimal = new BigDecimal(valueStr);
                    value = bigDecimal.setScale(accuracy, BigDecimal.ROUND_HALF_UP);
                    aggSumVO.setValue(value);
                }
                numCountList.addAll(aggSumList);
            }
            if ( !avgList.isEmpty() ) {
                // 求平均值后加百分比
                List<AggSumVO> aggAvgList = new ArrayList<>();
                Integer saasMark = formDataSummaryDTO.getSaasMark();
                if ( SaasMarkEnum.SAAS.getCode().equals(saasMark) ) {
                    aggAvgList = saasListHelp.avgBySumList(numCountList, formDataSummaryDTO, avgList, searchQuery);
                }
                numCountList.addAll(aggAvgList);
            }
            Iterator<AggSumVO> iterator = numCountList.iterator();
            while (iterator.hasNext()) {
                AggSumVO item = iterator.next();
                FieldAttrEntity fieldAttrEntity = explainMap.get(item.getAttr());
                if ( Objects.isNull(fieldAttrEntity.getSummaryFlag()) || Objects.equals(fieldAttrEntity.getSummaryFlag(), SummaryTypeEnum.NONE.getType()) ) {
                    iterator.remove();
                    continue;
                }
                if ( Objects.equals(fieldAttrEntity.getAmountFlag(), AmountFlagEnum.YES.getType()) ) {
                    // 金额需要设置千分位
                    Integer accuracy = fieldAttrEntity.getAccuracy();
                    if ( Objects.equals(1, fieldAttrEntity.getIntegerOnly()) ) {
                        accuracy = 0;
                    }
                    item.setValue(AttrDecimalPrecisionHelper.parseThousandth(item.getValue(), accuracy));
                }
            }
            for ( AggSumVO aggSumVO : numCountList ) {
                if ( noPermissionSet.contains(aggSumVO.getAttr()) ) {
                    aggSumVO.setValue("--");
                }
            }
        } catch (Exception e) {
            LOG.error("获取汇总失败：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return numCountList;
    }

    /**
     * 汇总子表单中的数字字段
     *
     * @param
     * @param
     * @return
     * @throws XbbException
     */
    public List<AggSumVO> getSubNumCount(FieldAttrEntity fieldAttrEntity, FormDataSubSummaryGetDTO formDataSubSummaryGetDTO) throws XbbException {
        List<AggSumVO> numCountList = new ArrayList<>();
        Set<String> noPermissionSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 盘点单等id
        Long refId = formDataSubSummaryGetDTO.getDataId();
        String attr = formDataSubSummaryGetDTO.getAttr();
        String corpid = formDataSubSummaryGetDTO.getCorpid();
        String userId = formDataSubSummaryGetDTO.getUserId();
        Integer fieldType = fieldAttrEntity.getFieldType();
        Integer businessType = formDataSubSummaryGetDTO.getBusinessType();
        Boolean fromPrint = Objects.equals(formDataSubSummaryGetDTO.getFromPrint(), 1);
        Boolean isSubForm = Objects.equals(fieldType,FieldTypeEnum.SUB_FORM.getType());
        Boolean isSelectProduct = Objects.equals(fieldType,FieldTypeEnum.SELECT_PRODUCT.getType());
        Boolean isApprovePrint = Objects.equals(formDataSubSummaryGetDTO.getApprovePrint(),1);
        try {
            if (isSelectProduct){
                proFormHelp.setProductAccuracy(fieldAttrEntity,corpid,userId);
            }
            // 保险起见 避免npe
            if (Objects.isNull(fieldAttrEntity.getSubForm()) || Objects.isNull(fieldAttrEntity.getSubForm().getItems())){
                return numCountList;
            }
            List<FieldAttrEntity> subExplainList = JSONArray.parseArray(JSON.toJSONString(fieldAttrEntity.getSubForm().getItems()), FieldAttrEntity.class);
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(subExplainList.size());
            List<AggSumDTO> subSumList = new ArrayList<>();
            BusinessProductTableNameEnum businessProductTableNameEnum = BusinessProductTableNameEnum.getTableNameByCode(businessType);
            String creatorId = null;
            List<String> ownerId = new ArrayList<>();
            List<String> coUserId = new ArrayList<>();
            if(!isApprovePrint && Objects.nonNull(refId) && !Objects.equals(refId,0L)){
                List<UserTeamEntity> userTeamEntities = userTeamHelp.getUserTeamList(Arrays.asList(refId), corpid, businessType, false, null);
                for (UserTeamEntity userTeamEntity : userTeamEntities) {
                    Integer isMain = userTeamEntity.getIsMain();
                    String teamUserId = userTeamEntity.getUserId();
                    if (Objects.equals(isMain, BasicConstant.MAIN_USER)) {
                        ownerId.add(teamUserId);
                    } else if (Objects.equals(isMain, BasicConstant.COOP_USER)) {
                        coUserId.add(teamUserId);
                    }
                }
                // 审批打印的时候dataid没穿 避免下面的空指针
                switch(businessProductTableNameEnum){
                    case INVENTORY_PRODUCT:
                        InventoryEntityExt entityExt = inventoryModel.getByKey(refId,corpid);
                        creatorId = entityExt.getCreatorId();
                        ownerId = Arrays.asList(entityExt.getOwnerId());
                        break;
                    case OPPORTUNITY_PRODUCT:
                        OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(refId,corpid);
                        creatorId = opportunityEntityExt.getCreatorId();
                        break;
                    case CONTRACT_PRODUCT:
                        ContractEntityExt contractEntityExt = contractModel.getByKey(refId,corpid);
                        creatorId = contractEntityExt.getCreatorId();
                        break;
                    case PURCHASE_PRODUCT:
                        PurchaseEntityExt purchaseEntityExt = purchaseModel.getByKey(refId,corpid);
                        creatorId = purchaseEntityExt.getCreatorId();
                        break;
                    // todo 待补充
                    case TRANSFER_PRODUCT:
                        TransferEntityExt transferEntityExt = transferModel.getByKey(refId,corpid);
                        creatorId = transferEntityExt.getCreatorId();
                        ownerId = Arrays.asList(transferEntityExt.getOwnerId());
                        break;
                    case ASSEMBLE_PRODUCT:
                        AssembleEntityExt assembleEntityExt = assembleModel.getByKey(refId,corpid);
                        creatorId = assembleEntityExt.getCreatorId();
                        ownerId  = Arrays.asList(assembleEntityExt.getOwnerId());
                        break;
                    case WORKORDER_PRODUCT:
                        WorkOrderEntity workOrderEntity = workOrderModel.getByKey(refId,corpid);
                        creatorId = workOrderEntity.getCreatorId();
                        break;
                    case COST_ADJUST_PRODUCT:
                        CostAdjustEntityExt costAdjustEntityExt = costAdjustModel.getByKey(refId,corpid);
                        ownerId = Collections.singletonList(costAdjustEntityExt.getOwnerId());
                        break;
                    default:
                        break;
                }
            }
            for ( FieldAttrEntity item : subExplainList ) {
                // 不是数字类型的，不进行汇总
                if ( !item.getFieldType().equals(FieldTypeEnum.NUM.getType()) ) {
                    continue;
                }
                // 不可见 不汇总
                if ( !Objects.equals(item.getVisible(),1) ) {
                    continue;
                }
                // fix:客户未勾选汇总时不进行汇总
                if (!Objects.equals(item.getSummaryFlag(), SummaryTypeEnum.SUM.getType())) {
                    continue;
                }
                // TODO 这里的权限判断有问题
                if ( !hasSubSumPermission(item, formDataSubSummaryGetDTO.getLoginUser(),creatorId,ownerId,coUserId) ) {
                    noPermissionSet.add(item.getAttr());
                }
                if ( !Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), formDataSubSummaryGetDTO.getBusinessType())
                        && Objects.equals(item.getSummaryFlag(), SummaryTypeEnum.NONE.getType()) ) {
                    continue;
                }
                if ( Objects.equals(XbbRefTypeEnum.COST_ADJUST.getCode(), formDataSubSummaryGetDTO.getBusinessType())
                        && CostAdjustProductEnum.getUpdataInvisibleAttrList().contains(item.getAttr()) ) {
                    continue;
                }
                AggSumDTO aggSumDTO = new AggSumDTO();
                if (isSubForm){
                    aggSumDTO.setAttr(item.getAttr());
                } else {
                    aggSumDTO.setAttr(item.getAttr());
                }
                aggSumDTO.setName(item.getAttrName());

                String field = item.getAttr();
                //预收款余额不在data里
                if ( !Objects.equals(XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode(), formDataSubSummaryGetDTO.getBusinessType()) ) {
                    if (isSubForm){
                        field = "data." + field;
                    }
                }
                aggSumDTO.setField(field);
                aggSumDTO.setFieldAttrEntity(item);
                if (isSubForm){
                    explainMap.put(formDataSubSummaryGetDTO.getAttr() + "." + item.getAttr(), item);
                } else {
                    explainMap.put(item.getAttr(), item);
                }
                subSumList.add(aggSumDTO);
                // BOM和盘点也需要转换
                List<Integer> stockList = new ArrayList<>(StockConstant.MULTI_UNIT_TYPE_LIST);
                stockList.add(XbbRefTypeEnum.BOM_BILL.getCode());
                stockList.add(XbbRefTypeEnum.INVENTORY.getCode());
                if (isSelectProduct && Objects.equals(field, SelectProductEnum.NUM.getAttr()) && (fromPrint || isApprovePrint) && stockList.contains(businessType)) {
                    AggSumDTO baseNumSumDTO = new AggSumDTO();
                    baseNumSumDTO.setField(SelectProductEnum.BUSINESS_NUM.getAttr());
                    baseNumSumDTO.setAttr(SelectProductEnum.BUSINESS_NUM.getAttr());
                    baseNumSumDTO.setName(SelectProductEnum.BUSINESS_NUM.getAttrName());
                    baseNumSumDTO.setFieldAttrEntity(item);
                    subSumList.add(baseNumSumDTO);
                }
            }

            if ( !subSumList.isEmpty() ) {
                if (isApprovePrint){
                    //审批打印汇总
                    List<AggSumVO> aggSumList = aggSumByFieldFromApprovePrint(attr,subSumList,formDataSubSummaryGetDTO,isSelectProduct);
                    for ( AggSumVO aggSumVO : aggSumList ) {
                        FieldAttrEntity field = explainMap.get(aggSumVO.getAttr());
                        if (Objects.equals(aggSumVO.getAttr(), SelectProductEnum.BUSINESS_NUM.getAttr())) {
                            field = explainMap.get(SelectProductEnum.NUM.getAttr());
                        }
                        if (Objects.isNull(field)) {
                             continue;
                        }
                        Integer accuracy = Objects.equals(1, field.getIntegerOnly()) || field.getAccuracy() == null ? 0 : field.getAccuracy();
                        Object value = aggSumVO.getValue();
                        if (Objects.isNull(value)){
                            continue;
                        }
                        String valueStr = String.valueOf(value);
                        BigDecimal bigDecimal = new BigDecimal(valueStr);
                        value = bigDecimal.setScale(accuracy, BigDecimal.ROUND_HALF_UP);
                        aggSumVO.setValue(value);
                    }
                    numCountList.addAll(aggSumList);
                } else {
                    // 普通子表单汇总走ES
                    if (isSubForm){
                        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
                        BoolQueryBuilder boolQueryBuilder = boolQuery();
                        // 拼接appId，菜单id等数据
                        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                        boolQueryBuilder.filter(termQuery("formId", formDataSubSummaryGetDTO.getFormId()));
                        boolQueryBuilder.filter(termQuery("dataId", formDataSubSummaryGetDTO.getDataId()));
                        // 查询自定义子表单时需加上attr的筛选
                        boolQueryBuilder.filter(termQuery("attr.keyword", fieldAttrEntity.getAttr()));
                        boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
                        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
                        NativeSearchQuery searchQuery = nativeSearchQueryBuilder.build();
                        IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(formDataSubSummaryGetDTO.getCorpid(), formDataSubSummaryGetDTO.getBusinessType(), formDataSubSummaryGetDTO.getSaasMark());
                        List<AggSumVO> aggSumList = esHelper.aggSumByField(indexTypeEnum.getIndex(), indexTypeEnum.getType(), subSumList, searchQuery);
                        for ( AggSumVO aggSumVO : aggSumList ) {
                            String key = aggSumVO.getAttr();
                            if (attr.contains(FieldTypeEnum.SUB_FORM.getEsalias())) {
                                key = attr + StringConstant.POINT + aggSumVO.getAttr();
                            }
                            FieldAttrEntity field = explainMap.get(key);
                            Integer accuracy = Objects.equals(1, field.getIntegerOnly()) || field.getAccuracy() == null ? 0 : field.getAccuracy();
                            Object value = aggSumVO.getValue();
                            String valueStr = String.valueOf(value);
                            BigDecimal bigDecimal = new BigDecimal(valueStr);
                            value = bigDecimal.setScale(accuracy, BigDecimal.ROUND_HALF_UP);
                            aggSumVO.setValue(value);
                        }
                        numCountList.addAll(aggSumList);
                    }
                    if (isSelectProduct){
                        // 关联产品汇总走mysql
                        List<AggSumVO> aggSumList = aggSumByFieldFromDB(attr,businessProductTableNameEnum,subSumList,corpid,refId, fromPrint);
                        for ( AggSumVO aggSumVO : aggSumList ) {
                            FieldAttrEntity field = explainMap.get(Objects.equals(aggSumVO.getAttr(), SelectProductEnum.BUSINESS_NUM.getAttr()) ? SelectProductEnum.NUM.getAttr() : aggSumVO.getAttr());
                            Integer accuracy = Objects.equals(1, field.getIntegerOnly()) || field.getAccuracy() == null ? 0 : field.getAccuracy();
                            Object value = aggSumVO.getValue();
                            value = Objects.isNull(value) ? 0.0D : value;
                            String valueStr = String.valueOf(value);
                            BigDecimal bigDecimal = new BigDecimal(valueStr);
                            value = bigDecimal.setScale(accuracy, BigDecimal.ROUND_HALF_UP);
                            aggSumVO.setValue(value);
                        }
                        numCountList.addAll(aggSumList);
                    }
                }
            }

            Iterator<AggSumVO> iterator = numCountList.iterator();
            while (iterator.hasNext()) {
                AggSumVO item = iterator.next();
                String key = item.getAttr();
                // 2020-11-12日 给李杰合并代码提交的，逻辑不清楚emm
                if (attr.contains(FieldTypeEnum.SUB_FORM.getEsalias())) {
                    key = attr + StringConstant.POINT + item.getAttr();
                } else if (Objects.equals(key, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                    key = SelectProductEnum.NUM.getAttr();
                }
                FieldAttrEntity entity = explainMap.get(key);
                if ( Objects.equals(entity.getSummaryFlag(), SummaryTypeEnum.NONE.getType()) ) {
                    iterator.remove();
                    continue;
                }
                item.setAttr(item.getAttr().substring(item.getAttr().indexOf(".") + 1));
                if ( Objects.equals(entity.getAmountFlag(), AmountFlagEnum.YES.getType()) ) {
                    // 金额需要设置千分位
                    Integer accuracy = entity.getAccuracy();
                    if ( Objects.equals(1, entity.getIntegerOnly()) ) {
                        accuracy = 0;
                    }
                    item.setValue(AttrDecimalPrecisionHelper.parseThousandth(item.getValue(), accuracy));
                }
            }
            for ( AggSumVO aggSumVO : numCountList ) {
                if ( noPermissionSet.contains(aggSumVO.getAttr()) ) {
                    aggSumVO.setValue("--");
                }
            }
            // 审批打印模板
            List<AggSumVO> oldAttrnumCountList = new ArrayList<>();
            for ( AggSumVO aggSumVO : numCountList ) {
                AggSumVO oldAttrAggSumVO = new AggSumVO();
                String key = aggSumVO.getAttr();
                Object value = aggSumVO.getValue();
                FieldAttrEntity fieldAttr = explainMap.get(key);
                if (Objects.nonNull(fieldAttr) && Objects.equals(0,fieldAttr.getIsRedundant())){
                    String oldAttrkey = ProductPrintHelpEnum.getOldAttrByNewAttr(key);
                    oldAttrAggSumVO.setAttr(oldAttrkey);
                    oldAttrAggSumVO.setValue(value);
                    oldAttrnumCountList.add(oldAttrAggSumVO);
                }
            }
            numCountList.addAll(oldAttrnumCountList);
        } catch (Exception e) {
            LOG.error("获取汇总失败：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return numCountList;
    }

    /**
     * 审批打印汇总
     * @param attr 标识哪个子表单 如subForm_1
     * @param subSumList 需要汇总的字段attr 如num_1 num_2
     * @param
     * @return
     * @throws XbbException
     */
    private List<AggSumVO> aggSumByFieldFromApprovePrint(String attr, List<AggSumDTO> subSumList, FormDataSubSummaryGetDTO formDataSubSummaryGetDTO, boolean isSelectProduct) throws XbbException{
        List<AggSumVO> aggSumList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        JSONObject data;

        Integer isWorkflow = formDataSubSummaryGetDTO.getIsWorkflow();

        if (Objects.isNull(isWorkflow)) {
            if (commonHelp.isOpenWorkFlow(formDataSubSummaryGetDTO.getCorpid())) {
                // 新工作流
                WorkflowNodeTaskGetDTO workflowNodeTaskGetDTO = new WorkflowNodeTaskGetDTO();
                BeanUtil.copyProperties(formDataSubSummaryGetDTO, workflowNodeTaskGetDTO);
                WorkflowNodeTaskGetVO workflowNodeTaskGetVO = workflowApproveListPageOperationService.detail(workflowNodeTaskGetDTO);
                data = workflowNodeTaskGetVO.getData();
            } else {
                ProcessNodeTaskGetDTO processNodeTaskGetDTO = new ProcessNodeTaskGetDTO();
                BeanUtil.copyProperties(formDataSubSummaryGetDTO,processNodeTaskGetDTO);
                ProcessNodeTaskGetVO processNodeTaskGetVO = paasProcessNodeTaskService.detail(processNodeTaskGetDTO);
                data = processNodeTaskGetVO.getData();
            }
        } else {
            if (Objects.equals(isWorkflow, BasicConstant.ONE)) {
                // 新工作流
                WorkflowNodeTaskGetDTO workflowNodeTaskGetDTO = new WorkflowNodeTaskGetDTO();
                BeanUtil.copyProperties(formDataSubSummaryGetDTO, workflowNodeTaskGetDTO);
                WorkflowNodeTaskGetVO workflowNodeTaskGetVO = workflowApproveListPageOperationService.detail(workflowNodeTaskGetDTO);
                data = workflowNodeTaskGetVO.getData();
            } else {
                ProcessNodeTaskGetDTO processNodeTaskGetDTO = new ProcessNodeTaskGetDTO();
                BeanUtil.copyProperties(formDataSubSummaryGetDTO,processNodeTaskGetDTO);
                ProcessNodeTaskGetVO processNodeTaskGetVO = paasProcessNodeTaskService.detail(processNodeTaskGetDTO);
                data = processNodeTaskGetVO.getData();
            }
        }

        JSONArray subFormData = data.getJSONArray(attr);
        Map<String,Double> valueMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 内存汇总
        if (Objects.nonNull(subFormData)){
            for (int i = 0;i < subFormData.size();i++) {
                JSONObject jsonObject = subFormData.getJSONObject(i);
                for (AggSumDTO aggSumDTO : subSumList) {
                    String field = aggSumDTO.getAttr();
                    String str = field;
                    // 普通子表单 走
                    if(field!=null && field.contains(".")){
                        str = field.substring(field.indexOf(".") + 1);
                    }
                    Double value = jsonObject.getDouble(str);
                    if (isSelectProduct) {
                        if (Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                            value = jsonObject.getDouble(SelectProductEnum.NUM.getAttr());
                        } else if (Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                            value = jsonObject.getDouble(SelectProductEnum.BUSINESS_NUM.getAttr());
                            if (Objects.equals(jsonObject.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr()), 0)) {
                                value = jsonObject.getDouble(SelectProductEnum.NUM.getAttr());
                            }
                        } else if (Objects.equals(field, SelectProductEnum.COST.getAttr()) && Objects.nonNull(jsonObject.get(SelectProductEnum.BUSINESS_COST.getAttr()))) {
                            value = jsonObject.getDouble(SelectProductEnum.BUSINESS_COST.getAttr());
                        } else if (Objects.equals(field, SelectProductEnum.SELLING_PRICE.getAttr()) && Objects.nonNull(jsonObject.get(SelectProductEnum.BUSINESS_SELLING_PRICE.getAttr()))) {
                            value = jsonObject.getDouble(SelectProductEnum.BUSINESS_SELLING_PRICE.getAttr());
                        } else if (Objects.equals(field, SelectProductEnum.PRICE.getAttr()) && Objects.nonNull(jsonObject.get(SelectProductEnum.BUSINESS_PRICE.getAttr()))) {
                            value = jsonObject.getDouble(SelectProductEnum.BUSINESS_PRICE.getAttr());
                        }
                    }
                    Double oldValue = valueMap.getOrDefault(field,0.0D);
                    Double newValue = Objects.isNull(value) ? oldValue : Arith.add(value, oldValue);
                    valueMap.put(field,newValue);
                }
            }
        }
        if (valueMap.containsKey(SelectProductEnum.BUSINESS_NUM.getAttr()) && Objects.equals(valueMap.get(SelectProductEnum.BUSINESS_NUM.getAttr()), 0D)) {
            valueMap.put(SelectProductEnum.BUSINESS_NUM.getAttr(), valueMap.get(SelectProductEnum.NUM.getAttr()));
        }
        // 封装汇总数据
        Iterator<Map.Entry<String,Double>> iterator = valueMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String,Double> entry = iterator.next();
            AggSumVO aggSumVO = new AggSumVO();
            String key = entry.getKey();
            Double value = entry.getValue();
            aggSumVO.setAttr(key);
            aggSumVO.setValue(value);
            aggSumList.add(aggSumVO);
        }
        return aggSumList;
    }

    /**
     *
     * @param attr 哪个子表单
     * @param businessProductTableNameEnum
     * @param subSumList 需要汇总的字段
     * @param corpid
     * @param refId 数据id如盘点单id
     * @return
     */
    private List<AggSumVO> aggSumByFieldFromDB(String attr,BusinessProductTableNameEnum businessProductTableNameEnum,List<AggSumDTO> subSumList,String corpid,Long refId, boolean fromPrint) throws XbbException{
        List<AggSumVO> aggSumList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<Long> productIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        JSONObject data = new JSONObject();
        Integer type = null;
        switch(businessProductTableNameEnum){
            case SUPPLIER_PRODUCT:
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = supplierProductModel.summaryByAttr("$." + field,corpid,refId,null);
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case QUOTATION_PRODUCT:
                QuotationEntityExt quotationEntityExt = quotationModel.getByKey(refId,corpid);
                data = quotationEntityExt.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = quotationProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn);
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case INVENTORY_PRODUCT:
                InventoryEntityExt inventoryEntityExt = inventoryModel.getByKey(refId,corpid);
                data = inventoryEntityExt.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = inventoryProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<InventoryProductEntity> inventoryProductEntities= inventoryProductModel.getProductsByInventoryId(refId,corpid);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = inventoryService.formatProduct4DetailShow(inventoryProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if (Objects.equals(field, InventoryProductEnum.NUM.getAttr())){
                        if (hasChanceIsOldData){
                            value = inventoryProductModel.summaryByAttrFromOutSide( "product_num", corpid, refId, productIdIn);
                        }
                    } else if (Objects.equals(field, InventoryProductEnum.GUARANTEE_PERIOD.getAttr())){
                        if (hasChanceIsOldData){
                            value = inventoryProductModel.summaryByAttrFromOutSide( "guarantee_period", corpid, refId, productIdIn);
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case OPPORTUNITY_PRODUCT:
                OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(refId,corpid);
                data = opportunityEntityExt.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = opportunityProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<OpportunityProductEntity> opportunityProductEntities = opportunityProductModel.getProductsByOppId(refId,corpid);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = opportunityService.formatProduct4DetailShow(opportunityProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if (Objects.equals(field, SelectProductEnum.NUM.getAttr())){
                        if (hasChanceIsOldData){
                            value = opportunityProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn);
                        }
                    } else if (Objects.equals(field, SelectProductEnum.PRICE.getAttr())){
                        if (hasChanceIsOldData){
                            value = opportunityProductModel.summaryByAttrFromOutSide("historical_price",corpid,refId,productIdIn);
                        }
                    } else if (Objects.equals(field, SelectProductEnum.SELLING_PRICE.getAttr())){
                        if (hasChanceIsOldData){
                            value = opportunityProductModel.summaryByAttrFromOutSide("price",corpid,refId,productIdIn);
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case CONTRACT_PRODUCT:
                ContractEntityExt contractEntityExt = contractModel.getByKey(refId,corpid);
                data = contractEntityExt.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = contractProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn,XbbRefTypeEnum.CONTRACT.getCode());
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<ContractProductEntity> contractProductEntities = contractProductModel.getProductsByConId(refId,corpid);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = contractService.formatProduct4DetailShow(contractProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if (Objects.equals(field, SelectProductEnum.NUM.getAttr())){
                        if (hasChanceIsOldData){
                            value = contractProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn,XbbRefTypeEnum.CONTRACT.getCode());
                        }
                    } else if (Objects.equals(field, SelectProductEnum.PRICE.getAttr())){
                        if (hasChanceIsOldData){
                            value = contractProductModel.summaryByAttrFromOutSide("historical_price",corpid,refId,productIdIn,XbbRefTypeEnum.CONTRACT.getCode());
                        }
                    } else if (Objects.equals(field, SelectProductEnum.SELLING_PRICE.getAttr())){
                        if (hasChanceIsOldData){
                            value = contractProductModel.summaryByAttrFromOutSide("price",corpid,refId,productIdIn,XbbRefTypeEnum.CONTRACT.getCode());
                        }
                    }else if (Objects.equals(field, SelectProductEnum.OUTSTOCK_NUM.getAttr())){
                        value = contractProductModel.summaryByAttrFromOutSide("outstock_num",corpid,refId,productIdIn,XbbRefTypeEnum.CONTRACT.getCode());
                    } else if (Objects.equals(field, SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr())){
                        value = contractProductModel.calcuateByAttrFromOutSide("product_num","outstock_num",corpid,refId,productIdIn,XbbRefTypeEnum.CONTRACT.getCode());
                        if (Objects.nonNull(value)) {
                            value = value < 0 ? 0 : value;
                        }
                    }else if (Objects.equals(field, SelectProductEnum.RETURN_NUM.getAttr())){
                        value = contractProductModel.summaryByAttrFromOutSide("instock_num",corpid,refId,productIdIn,XbbRefTypeEnum.CONTRACT.getCode());
                    } else if (hasChanceIsOldData && Objects.equals(field, SelectProductEnum.SUBTOTAL.getAttr())){
                        Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        modelMap.put(ParameterConstant.CORPID, corpid);
                        modelMap.put(ParameterConstant.CONTRACT_ID, refId);
                        modelMap.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                        modelMap.put("columns", "product_num, price");
                        List<ContractProductEntity> contractProductEntities = contractProductModel.findEntitys(modelMap);

                        Double count = 0D;
                        for (ContractProductEntity productEntity : contractProductEntities) {
                            Double productNum = productEntity.getProductNum() != null ? productEntity.getProductNum(): 0D;
                            Double price = productEntity.getPrice() == null ? 0D : productEntity.getPrice();
                            double priceTotal = Arith.mul(productNum, price);
                            count = Arith.add(priceTotal, count);
                        }
                        value = count;
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
                 //退货退款
            case REFUND_PRODUCT:
                RefundEntityExt refundEntityExt = refundModel.getByKey(refId,corpid);
                data = refundEntityExt.getData();
                Long redContractId = null;
                try{
                    redContractId = data.getLong(RefundEnum.RED_CONTRACT_ID.getAttr());
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = contractProductModel.summaryByAttr("$." + field,corpid,redContractId,null,XbbRefTypeEnum.REFUND.getCode());
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<ContractProductEntity> contractProductEntities = contractProductModel.getProductsByConId(redContractId,corpid);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = refundService.formatProduct4DetailShow(contractProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    }else if (Objects.equals(field, SelectProductEnum.INSTOCK_NUM.getAttr())){
                        value = contractProductModel.summaryByAttrFromOutSide("instock_num",corpid,redContractId,null,XbbRefTypeEnum.REFUND.getCode());
                    }else if (Objects.equals(field, SelectProductEnum.WAIT_INSTOCK_NUM.getAttr())){
                        value = contractProductModel.calcuateByAttrFromOutSide("product_num", "instock_num",corpid,redContractId,null,XbbRefTypeEnum.REFUND.getCode());
                        if (Objects.nonNull(value)) {
                            value = Math.abs(value);
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case PURCHASE_PRODUCT:
                PurchaseEntityExt purchaseEntityExt = purchaseModel.getByKey(refId,corpid);
                data = purchaseEntityExt.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = purchaseProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<PurchaseProductEntity> purchaseProductEntities = purchaseProductModel.getProductsByPurchaseId(corpid,refId);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = purchaseService.formatProduct4DetailShow(purchaseProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if (Objects.equals(field, SelectProductEnum.NUM.getAttr())){
                        if(hasChanceIsOldData){
                            value = purchaseProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn);
                        }
                    } else if(Objects.equals(field, SelectProductEnum.PRICE.getAttr())){
                        if(hasChanceIsOldData){
                            value = purchaseProductModel.summaryByAttrFromOutSide("product_price",corpid,refId,productIdIn);
                        }
                    } else if(Objects.equals(field, SelectProductEnum.INSTOCK_NUM.getAttr())){
                        value = purchaseProductModel.summaryByAttrFromOutSide("instock_num",corpid,refId,productIdIn);
                    } else if(Objects.equals(field, SelectProductEnum.WAIT_INSTOCK_NUM.getAttr())){
                        value = purchaseProductModel.calcuateByAttrFromOutSide("product_num", "instock_num",corpid,refId,productIdIn);
                        if (Objects.nonNull(value)) {
                            value = value < 0 ? 0 : value;
                        }
                    } else if(Objects.equals(field, SelectProductEnum.RETURN_NUM.getAttr())){
                        value = purchaseProductModel.summaryByAttrFromOutSide("outstock_num",corpid,refId,productIdIn);
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case TRANSFER_PRODUCT:
                TransferEntityExt transferEntityExt = transferModel.getByKey(refId,corpid);
                data = transferEntityExt.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = transferProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<TransferProductEntity> transferProductEntities = transferProductModel.getProductsByTransferId(refId,corpid);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = transferService.formatProduct4DetailShow(transferProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if (Objects.equals(field, TransferProductEnum.NUM.getAttr())){
                        if (hasChanceIsOldData){
                            value = transferProductModel.summaryByAttrFromOutSide( "product_num", corpid, refId, productIdIn);
                        }
                    } else if (Objects.equals(field, TransferProductEnum.GUARANTEE_PERIOD.getAttr())){
                        if (hasChanceIsOldData){
                            value = transferProductModel.summaryByAttrFromOutSide( "guarantee_period", corpid, refId, productIdIn);
                        }
                    } else if (Objects.equals(field, TransferProductEnum.OUTSTOCK_NUM.getAttr())){
                            value = transferProductModel.summaryByAttrFromOutSide( "outstock_num", corpid, refId, productIdIn);
                    } else if (Objects.equals(field, TransferProductEnum.INSTOCK_NUM.getAttr())){
                        value = transferProductModel.summaryByAttrFromOutSide( "instock_num", corpid, refId, productIdIn);
                    }else if (Objects.equals(field, TransferProductEnum.WAIT_INSTOCK_NUM.getAttr())){
                        value = transferProductModel.calcuateByAttrFromOutSide("outstock_num", "instock_num", corpid, refId, productIdIn);
                        if (Objects.nonNull(value)) {
                            value = value < 0 ? 0 : value;
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case ASSEMBLE_PRODUCT:
                AssembleEntityExt assembleEntityExt = assembleModel.getByKey(refId,corpid);
                data = assembleEntityExt.getData();
                try{
                    if (Objects.equals(AssembleEnum.OUT_PRODUCTS.getAttr(),attr)){
                        type = 1;
                    } else if (Objects.equals(AssembleEnum.IN_PRODUCTS.getAttr(),attr)){
                        type = 2;
                    }
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = assembleProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn,type);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        modelMap.put(ParameterConstant.CORPID, corpid);
                        modelMap.put(ParameterConstant.ASSEMBLE_ID, refId);
                        modelMap.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                        modelMap.put(ParameterConstant.TYPE, type);
                        List<AssembleProductEntity> assembleProductEntities = assembleProductModel.findEntitys(modelMap);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = assembleService.formatProduct4DetailShow(assembleProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            // todo 库存数量 通过productIdIn来确定最终库存数量
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            if(Objects.nonNull(productIdIn) && productIdIn.contains(jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr()))){
                                value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                            }
                        }
                    } else if (Objects.equals(field, AssembleProductEnum.NUM.getAttr())){
                        if (hasChanceIsOldData){
                            value = assembleProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn,type);
                        }
                    } else if (Objects.equals(field, AssembleProductEnum.GUARANTEE_PERIOD.getAttr())){
                        if (hasChanceIsOldData){
                            value = assembleProductModel.summaryByAttrFromOutSide("guarantee_period",corpid,refId,productIdIn,type);
                        }
                    } else if (Objects.equals(field, AssembleProductEnum.COST.getAttr())){
                        if (hasChanceIsOldData){
                            value = assembleProductModel.summaryByAttrFromOutSide("cost",corpid,refId,productIdIn,type);
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    // TODO 成本小计
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case WORKORDER_PRODUCT:
                WorkOrderEntity workOrderEntity = workorderModel.getByKey(refId,corpid);
                data = workOrderEntity.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = workOrderProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<WorkOrderProductEntity> workOrderProductEntities = workOrderProductModel.getProductsByWorkOrderId(refId,corpid);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = workOrderService.formatProduct4DetailShow(workOrderProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if (Objects.equals(field, WorkOrderProductEnum.NUM.getAttr())){
                        if(hasChanceIsOldData){
                            value = workOrderProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn);
                        }
                    } else if (Objects.equals(field, WorkOrderProductEnum.PRICE.getAttr())){
                        if(hasChanceIsOldData){
                            value = workOrderProductModel.summaryByAttrFromOutSide("product_price",corpid,refId,productIdIn);
                        }
                    } else if (Objects.equals(field, WorkOrderProductEnum.OUTSTOCK_NUM.getAttr())){
                        value = workOrderProductModel.summaryByAttrFromOutSide( "outstock_num", corpid, refId, productIdIn);
                    } else if (Objects.equals(field, WorkOrderProductEnum.WAIT_OUTSTOCK_NUM.getAttr())){
                        value = workOrderProductModel.calcuateByAttrFromOutSide("product_num", "outstock_num", corpid, refId, productIdIn);
                        if (Objects.nonNull(value)) {
                            value = value < 0 ? 0 : value;
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case RETURNEDPURCHASE_PRODUCT:
                ReturnedPurchaseEntityExt returnedPurchaseEntityExt = returnedPurchaseModel.getByKey(refId,corpid);
                data = returnedPurchaseEntityExt.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = returnedPurchaseProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<ReturnedPurchaseProductEntity> returnedPurchaseProductEntities = returnedPurchaseProductModel.getProductsByRetPurchaseId(corpid,refId);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = returnedPurchaseService.formatProduct4DetailShow(returnedPurchaseProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if (Objects.equals(field, RefundProductEnum.NUM.getAttr())){
                        if (hasChanceIsOldData){
                            value = returnedPurchaseProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn);
                        }
                    } else if (Objects.equals(field, RefundProductEnum.PRICE.getAttr())){
                        if (hasChanceIsOldData){
                            value = returnedPurchaseProductModel.summaryByAttrFromOutSide("product_price",corpid,refId,productIdIn);
                        }
                    } else if(Objects.equals(field, SelectProductEnum.SUBTOTAL.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<ReturnedPurchaseProductEntity> returnedPurchaseProductEntities = returnedPurchaseProductModel.getProductsByRetPurchaseId(corpid,refId);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = returnedPurchaseService.formatProduct4DetailShow(returnedPurchaseProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.SUBTOTAL.getAttr());
                        }
                    }else if (Objects.equals(field, SelectProductEnum.OUTSTOCK_NUM.getAttr())){
                        value = returnedPurchaseProductModel.summaryByAttrFromOutSide( "outstock_num", corpid, refId, productIdIn);
                    } else if (Objects.equals(field, SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr())){
                        value = returnedPurchaseProductModel.calcuateByAttrFromOutSide("product_num", "outstock_num", corpid, refId, productIdIn);
                        if (Objects.nonNull(value)) {
                            value = value < 0 ? 0 : value;
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case BOM_BILL_PRODUCT:
                BomBillEntityExt bomBillEntityExt = bomBillModel.getByKey(refId,corpid);
                data = bomBillEntityExt.getData();
                try{
                    if (Objects.equals(BomBillEnum.PRODUCT.getAttr(),attr)){
                        type = 1;
                    } else if (Objects.equals(BomBillEnum.MATERIEL.getAttr(),attr)){
                        type = 2;
                    }
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = bomProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn,type);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<BomProductEntity> bomProductEntities = bomProductModel.getProductsByBomId(refId,corpid,type);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = bomBillService.formatProduct4DetailShow(bomProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if (Objects.equals(field, SelectProductEnum.NUM.getAttr())){
                        if (hasChanceIsOldData){
                            value = bomProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn,type);
                        }
                    } else if (Objects.equals(field, SelectProductEnum.LOSS_RATE.getAttr())){
                        if (hasChanceIsOldData){
                            value = bomProductModel.summaryByAttrFromOutSide("attrition_rate",corpid,refId,productIdIn,type);
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case PRODUCTION_ORDER_PRODUCT:
                ProductionOrderEntityExt productionOrderEntity = productionOrderModel.getByKey(refId,corpid);
                data = productionOrderEntity.getData();
                try{
                    if (Objects.equals(ProductionOrderEnum.PRODUCT.getAttr(),attr)){
                        type = 1;
                    } else if (Objects.equals(ProductionOrderEnum.MATERIEL.getAttr(),attr)){
                        type = 2;
                    }
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = productionOrderProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn,type);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field, SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        Map<String, Object> modelMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        modelMap.put(ParameterConstant.CORPID, corpid);
                        modelMap.put(ParameterConstant.PRODUCTION_ORDER_ID, refId);
                        modelMap.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
                        modelMap.put(ParameterConstant.TYPE, type);
                        List<ProductionOrderProductEntity> productionOrderProductEntities = productionOrderProductModel.findEntitys(modelMap);
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = productionOrderService.formatProduct4DetailShow(productionOrderProductEntities,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        // todo 库存数量 通过productIdIn来确定最终库存数量
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            if(Objects.nonNull(productIdIn) && productIdIn.contains(jsonObject.getLong(SelectProductEnum.PRODUCT.getAttr()))){
                                value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                            }
                        }
                    } else if (Objects.equals(field, SelectProductEnum.NUM.getAttr())){
                        if(hasChanceIsOldData){
                            value = productionOrderProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn,type);
                        }
                    } else if (Objects.equals(field, SelectProductEnum.LOSS_RATE.getAttr())){
                        if(hasChanceIsOldData){
                            value = productionOrderProductModel.summaryByAttrFromOutSide("attrition_rate",corpid,refId,productIdIn,type);
                        }
                    }else if (Objects.equals(field, SelectProductEnum.OUTSTOCK_NUM.getAttr())){
                        value = productionOrderProductModel.summaryByAttrFromOutSide( "outstock_num", corpid, refId, productIdIn, type);
                    } else if (Objects.equals(field, SelectProductEnum.WAIT_OUTSTOCK_NUM.getAttr())){
                        value = productionOrderProductModel.calcuateByAttrFromOutSide("product_num", "outstock_num", corpid, refId, productIdIn, type);
                        if (Objects.nonNull(value)) {
                            value = value < 0 ? 0 : value;
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case PURCHASE_INSTOCK_PRODUCT:
            case REFUND_INSTOCK_PRODUCT:
            case OTHER_INSTOCK_PRODUCT:
            case PRODUCTION_INSTOCK_PRODUCT:
            case RETURNED_MATERIEL_INSTOCK_PRODUCT:
                InstockEntityExt instockEntityExt = instockModel.getByKey(refId,corpid);
                data = instockEntityExt.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = instockProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn);
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field,SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<InstockProductEntity> instockProductEntityList = instockProductModel.getProductsByInstockIdIn(corpid,Arrays.asList(refId));
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = instockService.formatProduct4DetailShow(instockProductEntityList,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if(Objects.equals(field,SelectProductEnum.NUM.getAttr())){
                        if (hasChanceIsOldData){
                            value = instockProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn);
                        }
                    } else if(Objects.equals(field,SelectProductEnum.GUARANTEE_PERIOD.getAttr())){
                        if (hasChanceIsOldData){
                            value = instockProductModel.summaryByAttrFromOutSide("guarantee_period",corpid,refId,productIdIn);
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;
            case CONTRACT_OUTSTOCK_PRODUCT:
            case RETURNED_PURCHASE_OUTSTOCK_PRODUCT:
            case OTHER_OUTSTOCK_PRODUCT:
            case PRODUCTION_MATERIEL_OUTSTOCK_PRODUCT:
            case WORK_ORDER_OUTSTOCK_PRODUCT:
                OutstockEntityExt outstockEntityExt = outstockModel.getByKey(refId,corpid);
                data = outstockEntityExt.getData();
                try{
                    JSONArray array = data.getJSONArray(attr);
                    if(Objects.nonNull(array)){
                        productIdIn = array.toJavaList(java.lang.Long.class);
                    }
                } catch (Exception e){
                    LOG.error("获取DB单据关联产品id出错", e);
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                }
                for (AggSumDTO aggSumDTO : subSumList){
                    String field = aggSumDTO.getAttr();
                    Double value = null;
                    if (Objects.equals(businessProductTableNameEnum, BusinessProductTableNameEnum.CONTRACT_OUTSTOCK_PRODUCT)) {
                        value = outstockProductModel.summaryByAttrContractOutStock("$." + field,corpid,refId,productIdIn);
                    } else {
                       value = outstockProductModel.summaryByAttr("$." + field,corpid,refId,productIdIn);
                    }
                    boolean hasChanceIsOldData = Objects.isNull(value) || Objects.equals(value, 0);
                    if (Objects.equals(field,SelectProductEnum.STOCK.getAttr())){
                        // 清零
                        value = 0.0D;
                        List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.getProductsByOutstockIdIn(corpid,Arrays.asList(refId));
                        PagingProductDTO pagingProductDTO = new PagingProductDTO();
                        pagingProductDTO.setCorpid(corpid);
                        DetailProductVO detailProductVO = outstockService.formatProduct4DetailShow(outstockProductEntityList,pagingProductDTO);
                        JSONArray jsonArray = detailProductVO.getProductDataArr();
                        for (int i = 0;i < jsonArray.size();i++){
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            value += jsonObject.getDouble(SelectProductEnum.STOCK.getAttr());
                        }
                    } else if (Objects.equals(field,SelectProductEnum.NUM.getAttr())){
                        if (hasChanceIsOldData){
                            value =  outstockProductModel.summaryByAttrFromOutSide("product_num",corpid,refId,productIdIn);
                        }
                    } else if (Objects.equals(field,SelectProductEnum.GUARANTEE_PERIOD.getAttr())){
                        if (hasChanceIsOldData){
                            value =  outstockProductModel.summaryByAttrFromOutSide("guarantee_period",corpid,refId,productIdIn);
                        }
                    } else if (Objects.equals(field, SelectProductEnum.RETURN_NUM.getAttr())){
                        if (hasChanceIsOldData) {
                            value = outstockProductModel.summaryByAttrFromOutSide( "instock_num", corpid, refId, productIdIn);
                        }
                    }
                    if (fromPrint && Objects.equals(field, SelectProductEnum.NUM.getAttr())) {
                        field = SelectProductEnum.BUSINESS_NUM.getAttr();
                    } else if (fromPrint && Objects.equals(field, SelectProductEnum.BUSINESS_NUM.getAttr())) {
                        field = SelectProductEnum.NUM.getAttr();
                    }
                    AggSumVO aggSumVO = new AggSumVO();
                    aggSumVO.setName(aggSumDTO.getName());
                    aggSumVO.setValue(value);
                    aggSumVO.setAttr(field);
                    aggSumList.add(aggSumVO);
                }
                break;

        }
        return aggSumList;
    }

    /**
     * 是否权限
     *
     * @param item
     * @param loginUser
     * @return true有权限, false无权限
     */
    private Boolean hasSumPermission(FieldAttrEntity item, UserVO loginUser) throws XbbException {
        if ( Objects.equals(item.getVisibleScopeEnable(), 1) && Objects.nonNull(item.getVisibleScopeRule())
                && Objects.nonNull(item.getVisibleScopeRule().getRelative()) && !item.getVisibleScopeRule().getRelative().isEmpty() ) {
            return false;
        }
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setLoginUser(loginUser);
        handlerExplainDTO.setUserId(loginUser.getUserId());
        return !ExplainUtil.invisibleOfScope(item, handlerExplainDTO);
    }

    /**
     * 子表单数据汇总是否权限 负责人 协同人 创建人
     *
     * @param item
     * @param loginUser
     * @return true有权限, false无权限
     */
    private Boolean hasSubSumPermission(FieldAttrEntity item, UserVO loginUser,String creatorId,List<String> ownerId,List<String> coUserId) throws XbbException {
//        if ( Objects.equals(item.getVisibleScopeEnable(), 1) && Objects.nonNull(item.getVisibleScopeRule().getRelative()) && !item.getVisibleScopeRule().getRelative().isEmpty() ) {
//            return false;
//        }
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        handlerExplainDTO.setLoginUser(loginUser);
        handlerExplainDTO.setUserId(loginUser.getUserId());
        handlerExplainDTO.setCreatorId(creatorId);
        handlerExplainDTO.setCoUserId(coUserId);
        handlerExplainDTO.setOwnerId(ownerId);
        return !ExplainUtil.invisibleOfScope(item, handlerExplainDTO);
    }

    @Override
    public FormDataGetVO get(FormDataGetDTO formDataGetDTO) throws XbbException {
        FormDataGetVO formDataGetVO = new FormDataGetVO();
        try {
            Integer businessType = formDataGetDTO.getBusinessType();
            String corpid = formDataGetDTO.getCorpid();
            Integer subBusinessType = formDataGetDTO.getSubBusinessType();
            Integer saasMark = formDataGetDTO.getSaasMark();
            Long dataId = formDataGetDTO.getDataId();
            UserVO loginUser = formDataGetDTO.getLoginUser();
            //经销商业务改businessType
            Integer distributorMark = formDataGetDTO.getDistributorMark();
            if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())){
                businessType = XbbRefTypeEnum.transferBusinessType4Distributor(businessType,distributorMark);
                formDataGetDTO.setBusinessType(businessType);
            }
            BusinessDetailBaseInfoService businessDetailBaseInfoService = businessDetailBasicInfoMap.get(businessType);
            if (Objects.nonNull(businessDetailBaseInfoService) && !Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), distributorMark)) {
                return businessDetailBaseInfoService.get(formDataGetDTO);
            }

            if ( Objects.nonNull(businessType) && Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                formDataGetVO = workOrderFormDataService.get(formDataGetDTO);
                return formDataGetVO;
            }
            //知识库条目详情
            if ( Objects.nonNull(businessType) && Objects.equals(businessType, XbbRefTypeEnum.KNOWLEDGE_BASE.getCode()) ) {
                formDataGetVO = knowledgeDataService.get(formDataGetDTO);
                return formDataGetVO;
            }
            PaasFormDataEntityExt paasFormDataEntityExt;
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
            boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
            if ( Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) ) {
                if (sheetFlag) {
                    paasFormDataEntityExt = proGetHelp.getByKey(dataId, sheetTypeEnum.getXbbRefTypeEnum().getCode(),saasMark, corpid);
                } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())){
                    // 产品编辑的时候一定要传父产品的id
                    paasFormDataEntityExt = saasGetHelp.getFormData(formDataGetDTO.getDataId(), formDataGetDTO.getCorpid(), XbbRefTypeEnum.PRODUCT.getCode());
                    if (paasFormDataEntityExt == null ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                    }
                    if (!Objects.equals(paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()), 0L) ) {
                        dataId = paasFormDataEntityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr());
                        formDataGetDTO.setDataId(dataId);
                        paasFormDataEntityExt = saasGetHelp.getFormData(dataId, formDataGetDTO.getCorpid(), XbbRefTypeEnum.PRODUCT.getCode());
                    }
                } else {
                    // 经销商查询特殊处理，businessType转回
                    Integer searchBusinessType = XbbRefTypeEnum.transferBusinessType2Index(businessType);
                    paasFormDataEntityExt = saasGetHelp.getFormData(dataId, corpid, searchBusinessType);
                }
                paasFormDataEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
            } else {
                // 没有saasMark标志的，现在全按paas应用来处理
                paasFormDataEntityExt = paasFormDataModel.getByKey(dataId, corpid);
                paasFormDataEntityExt.setSaasMark(SaasMarkEnum.PAAS.getCode());
            }
            if ( paasFormDataEntityExt == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            } else if ( Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel()) ) {
                if ( Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_DUPLICATE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_RECYCLE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_DUPLICATE.getCode())) {
                    // 回收站的del为1
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
            }
            //拼装富文本数据
            richTextService.addRichTextByDataId(dataId, corpid, formDataGetDTO.getFormId(),
                    Objects.equals(distributorMark, BasicConstant.ONE) ? XbbRefTypeEnum.transferBusinessType2Index(businessType) : businessType,
                    saasMark, paasFormDataEntityExt.getDel(), paasFormDataEntityExt.getData());

            // 工作报告的今日计划，明日计划重新取
            if (Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), businessType)) {
                JSONObject data = paasFormDataEntityExt.getData();
                List<WorkPlanEntity> thisPlanList = workReportModel.getThisPlansByTime(corpid, paasFormDataEntityExt.getCreatorId(),
                        getIntegerFromFormData(data, WorkReportFieldEnum.TYPE.getAttr()),
                        getIntegerFromFormData(data, WorkReportFieldEnum.REPORT_DATE.getAttr()));
                JSONArray thisPlan = new JSONArray();
                for (WorkPlanEntity entity : thisPlanList) {
                    JSONObject object = new JSONObject();
                    object.put(WorkReportPlanEnum.CONTENT.getAttr(), entity.getContent());
                    object.put(WorkReportPlanEnum.STATUS.getAttr(), entity.getStatus());
                    object.put(WorkReportPlanEnum.ID.getAttr(), entity.getId());
                    thisPlan.add(object);
                }
                List<WorkPlanEntity> nextPlanList = workReportModel.getNextPlansByTime(corpid, paasFormDataEntityExt.getCreatorId(),
                        getIntegerFromFormData(data, WorkReportFieldEnum.TYPE.getAttr()), paasFormDataEntityExt.getId());
                JSONArray nextPlan = new JSONArray();
                for (WorkPlanEntity entity : nextPlanList) {
                    JSONObject object = new JSONObject();
                    object.put(WorkReportPlanEnum.CONTENT.getAttr(), entity.getContent());
                    object.put(WorkReportPlanEnum.ID.getAttr(), entity.getId());
                    nextPlan.add(object);
                }

                data.put(WorkReportFieldEnum.THIS_PLAN.getAttr(), thisPlan);
                data.put(WorkReportFieldEnum.NEXT_PLAN.getAttr(), nextPlan);
            }

            Long formId = paasFormDataEntityExt.getFormId();
            HandlerExplainDTO handlerExplainDTO = initHandlerExplainDto(formDataGetDTO, paasFormDataEntityExt);
            VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(loginUser, paasFormDataEntityExt);
            boolean hasDataPermission = commonPermissionHelp.checkViewPermission(verifyViewPermissionDTO);
            if ( Objects.equals(formDataGetDTO.getPlatform(), StringConstant.PLATFORM_DINGTALK) ) {
                if ( Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode()) && !hasDataPermission) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                }
                if ( Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                    PaasFormEntityExt paasFormEntity = paasFormModel.getByKey(formId, corpid);
                    if ( Objects.equals(paasFormEntity.getEnable(), 0) || Objects.equals(paasFormEntity.getDel(), 1) ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                    }
                    List<PaasFormEntityExt> formList = new ArrayList<>();
                    formList.add(paasFormEntity);
                    paasFormService.removeByPermission(formList, loginUser);
                    if ( formList.isEmpty() ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                    }
                }
            }
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            if ( paasFormExplainEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            PaasFormEntityExt paasFormEntity = paasFormModel.getByKey(formId, corpid);
            if ( paasFormEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            // 渲染业务规则
            String creatorId = paasFormDataEntityExt.getCreatorId();
            //  获取字段解释信息，并且过滤不可见字段 start
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            //根据套餐判断负责人属性
            Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
            boolean ultimateTag = Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
            if(!ultimateTag && FormOwnerUniqueEnum.getDefaultBusinessList().contains(businessType)){
                //只有旗舰版支持负责人唯一设置，其他版本拿默认设置
                FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                Integer multiple = formOwnerUniqueEnum.getValue();
                for (FieldAttrEntity fieldAttrEntity : explainList) {
                    if(Objects.equals(fieldAttrEntity.getAttr(),FieldTypeEnum.OWNERID.getAlias())){
                        fieldAttrEntity.setMultiple(multiple);
                    }
                }
            }
            // 24188 【APP-产品】未开启进销存，产品详情页部分字段不应该展示
            if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                FilterAttrOnOffJXCDTO filterAttrOnOffJXCDTO = new FilterAttrOnOffJXCDTO();
                BeanUtil.copyProperties(formDataGetDTO, filterAttrOnOffJXCDTO);
                filterAttrOnOffJXCDTO.setFieldAttrEntityList(explainList);
                filterAttrOnOffJXCDTO.setOperatePageCode(OperatePageEnum.DETAIL.getCode());
                productModel.filterAttrOnOffJXC(filterAttrOnOffJXCDTO);
            }
            if (sheetFlag) {
                //如果是回/付款单，则根据数据data内的回/付款单类型重置sheetTypeEnum（前端传过来的businessType可能没有详细区分哪种类型回/付款单）
                sheetTypeEnum = fundHelp.getSheetTypeEnumByData(sheetTypeEnum, paasFormDataEntityExt.getData());
                fundHelp.handlePaymentSheet(false, sheetTypeEnum, explainList, corpid, distributorMark);
            }
            handlerExplainDTO.setCreatorId(creatorId);
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(formDataGetDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(explainList);
//            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
//            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
//            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            Map<String, UserEntity> userMap = handlerExplainDTO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = commonHelp.getDepMap(userAndDepartmentGetDTO);


            handlerExplainDTO.setPaasFormEntityExt(paasFormEntity);
            handlerExplainDTO.setFormData(paasFormDataEntityExt.getData());
            HandlerExplainVO handlerExplainVO = formDataDetailFormExplainHandleName.handleExplain(handlerExplainDTO);
            if ( handlerExplainVO == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            List<FieldAttrEntity> headList = handlerExplainVO.getHeadList();
            // 获取字段解释信息，并且过滤不可见字段 end
            if (Objects.equals(formDataGetDTO.getPlatform(),PlatFormEnum.DINGTALK.getValue()) && Objects.equals(formDataGetDTO.getBusinessType(),XbbRefTypeEnum.PRODUCT.getCode())){
                // 强制过滤调产品简介
                headList.removeIf(item -> Objects.equals(item.getAttr(),ProductEnum.INSTRUCTION.getAttr()));
            }
            formDataGetVO.setHeadList(headList);
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(headList.size());
            // 将字段放入字段容器
            for ( FieldAttrEntity fieldAttrEntity : headList ) {
                explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
            }
            // ---- 获取用户和部门容器start


            formDataGetVO.setFormList(paasFormDataEntityExt);
            JSONObject data = paasFormDataEntityExt.getData();
            saasExplainHandle(data, businessType, explainMap, corpid);
            // 设置系统字段
            // 设置创建者
            data.put(FieldTypeEnum.ADDTIME.getAlias(), paasFormDataEntityExt.getAddTime());
            data.put(FieldTypeEnum.UPDATETIME.getAlias(), paasFormDataEntityExt.getUpdateTime());
            data.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEntityExt.getSerialNo());
            data.put(FieldTypeEnum.CREATORID.getAlias(), creatorId);
            data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEntityExt.getDepartmentId());

            //  获取用户和部门容器 解析paas的特殊数据 end
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            BeanUtil.copyProperties(formDataGetDTO, parseSingleRowDataDTO);
            parseSingleRowDataDTO.setDataJsonObject(data);
            parseSingleRowDataDTO.setExplainMap(explainMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            // 解析数据
            ParseSingleRowDataVO parseSingleRowDataVO = formDataGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
            if ( Objects.isNull(parseSingleRowDataVO) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
            }
            LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
            linkResultDataVO = linkResultDataVO == null ? new LinkResultDataVO() : linkResultDataVO;
            linkResultDataVO.setUserMap(userMap);
            linkResultDataVO.setDepartmentMap(departmentMap);
            data = parseSingleRowDataVO.getResult();
            if ( !linkResultDataVO.getLinkData().isEmpty() && !linkResultDataVO.getLinkDataSet().isEmpty() ) {
                linkResultDataVO.setData(data);
                linkResultDataVO.setExplainMap(explainMap);
                linkResultDataVO.setExplainList(headList);
                data = formDataLinkDataGetServiceImpl.formDataLinkDataGet(formDataGetDTO, linkResultDataVO);
            }
            // 处理关联数据逻辑 end

            if ( Objects.equals(formDataGetDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode()) ) {
                // 详情特殊返回字段
                proDetailHandlerHelp.handleDetailSpecialField(data, paasFormDataEntityExt.getId(), businessType, corpid, explainMap, formDataGetDTO.getFormId(), handlerExplainDTO);
                // 详情特殊序列化解释
                proDetailHandlerHelp.handleDetailSpecialExplain(data, headList, businessType, formDataGetDTO.getPlatform(), corpid, formDataGetDTO.getFormId());
                FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
                BeanUtil.copyProperties(formDataGetDTO, formatExplainDTO);
                formatExplainDTO.setExplainList(headList);
                formatExplainDTO.setDataEntity(paasFormDataEntityExt);
                formatExplainDTO.setResult(data);
                // 编辑时saas字段显示特殊逻辑
                saasGetHelp.formatExplain(formatExplainDTO);
                headList = formatExplainDTO.getExplainList();
                SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
                BeanUtil.copyProperties(formDataGetDTO, saasAnalysisDataDTO);
                if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode()) ) {
                    //工作报告查询修改为工作报告提交人
                    saasAnalysisDataDTO.setUserId(creatorId);
                }
                // saas特殊格式转换
                saasGetHelp.formatData(saasAnalysisDataDTO, data);
                // saas特殊返回字段，放在一个对象中
                saasGetHelp.formatSaasAttrToReturn(formDataGetVO, formDataGetDTO, data);
                // 详情页基本信息特殊方法
                //saasGetHelp.getSpecialMethod(formDataGetVO, formDataGetDTO, data);
                // 解析saas pro的特殊数据，包括下拉框的回显
                PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
                List<PaasFormDataEntityExt> formDataEsEntities = new ArrayList<>();
                PaasFormDataEntityExt paasFormDataEsEntity = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(paasFormDataEntityExt, paasFormDataEsEntity);
                paasFormDataEsEntity.setData(data);
                formDataEsEntities.add(paasFormDataEsEntity);
                paasFormDataEsListVO.setBusinessType(businessType);
                paasFormDataEsListVO.setPaasFormDataESList(formDataEsEntities);
                saasListHelp.analysisSaasDataList(paasFormDataEsListVO, explainMap);
                formDataEsEntities = paasFormDataEsListVO.getPaasFormDataESList();
                data = formDataEsEntities.get(0).getData();
                //评分详情页get接口，移除评分字段，只在头部展示
                if(XbbRefTypeEnum.checkScoreBusinessType(businessType)){
                    String scoreFieldAttr = scoreRuleHelp.getScoreFieldAttr(businessType);
                    if(StringUtil.isNotEmpty(scoreFieldAttr)){
                        //key不存在只会返回空，不会抛异常影响主流程
                        data.remove(scoreFieldAttr);
                    }
                }
                // 移动端联系人头像不回显
                if (Objects.equals(PlatFormEnum.DINGTALK.getValue(), formDataGetDTO.getPlatform()) && Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), businessType)) {
                    data.remove(ContactEnum.AVATAR.getAttr());
                }

            } else {
                // 解析摘要
                paasFormDataEntityExt.setData(data);
                List<SummaryDataPoJo> summaryList = paasFormHelp.getSummaryList(paasFormEntity, explainMap, paasFormDataEntityExt);
                data.put("summaryList", summaryList);
                // 解析标题
                List<FormTitlePoJo> formTitleList = ExplainUtil.getFormTitle(JSONArray.parseArray(paasFormEntity.getCustomTitle()), explainMap, data, explainList, paasFormDataEntityExt);
                data.put("titleList", formTitleList);
                // 解析标签
                List<SummaryDataPoJo> labelsList = ExplainUtil.getSummaryList(paasFormEntity.getLabelsList(), data, explainMap, paasFormDataEntityExt);
                data.put("labelsList", labelsList);
            }
               formDataGetVO.setData(data);
            //PC端千份位为了防止数据操作转化问题单独在这里解析
            formDataGetAnalysisDataHelp.analysisGetOfThousandBits(formDataGetVO, explainList, false);
            // 子表单和tab相关处理
            HandlerExplainVO tabHandlerExplainVO = new HandlerExplainVO();
            tabHandlerExplainVO.setHeadList(headList);
            tabHandlerExplainVO.setSaasMark(saasMark);
            tabHandlerExplainVO.setBusinessType(businessType);
            if ( SaasMarkEnum.SAAS.getCode().equals(saasMark) && XbbRefTypeEnum.WORK_REPORT.getCode() == businessType ) {
                formDataGetVO.setHeadList(ExplainUtil.getFieldListWorkReport(tabHandlerExplainVO).getHeadList());
            } else {
                formDataGetVO.setHeadList(ExplainUtil.getFieldListNoIncludeSubForm(tabHandlerExplainVO).getHeadList());
            }
            // 移动端联系人头像不回传给前端，经产品高梦娜确认
            if (Objects.equals(PlatFormEnum.DINGTALK.getValue(), formDataGetDTO.getPlatform()) && Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) && Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), businessType)) {
                formDataGetVO.getHeadList().removeIf(item -> Objects.equals(ContactEnum.AVATAR.getAttr(), item.getAttr()));
            }
            /* ==================== 上部按钮权限 ==================== */

            formDataGetVO.setPaasFormEntity(paasFormEntity);
            if ( Objects.equals(businessType, XbbRefTypeEnum.INVOICE.getCode()) ) {
                List<InvoiceAmountDetailDTO> invoiceAmountDetailDTOList = invoiceCommonHelper.getAmountDetailBySalesInvoiceDataId(dataId,corpid);
                if(CollectionsUtil.isNotEmpty(invoiceAmountDetailDTOList)){
                    formDataGetVO.setAmountDetail(JSONArray.parseArray(JSONArray.toJSONString(invoiceAmountDetailDTOList)));
                }
                //关联回款类型下拉框字段ItemoPojo -> text
                data.put(InvoiceEnum.PAYMENT_RELATIONSHIP.getAttr(),commonHelp.formatFundStatusText(data,InvoiceEnum.PAYMENT_RELATIONSHIP.getAttr(),""));
            }else if(Objects.equals(businessType,XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                List<InvoiceAmountDetailDTO> invoiceAmountDetailDTOList = invoiceCommonHelper.getAmountDetailByInvoiceDataId(dataId,corpid);
                if(CollectionsUtil.isNotEmpty(invoiceAmountDetailDTOList)) {
                    formDataGetVO.setAmountDetail(JSONArray.parseArray(JSONArray.toJSONString(invoiceAmountDetailDTOList)));
                }
                data.put(PurchaseInvoiceEnum.PAY_RELATIONSHIP.getAttr(),commonHelp.formatFundStatusText(data,PurchaseInvoiceEnum.PAY_RELATIONSHIP.getAttr(),""));
            }
            if (sheetFlag) {
                JSONArray amountDetail = getAmountDetail4exist(sheetTypeEnum, parseSingleRowDataDTO, corpid, dataId, paasFormDataEntityExt);
                formDataGetVO.setAmountDetail(amountDetail);
            }
            if (Objects.equals(XbbRefTypeEnum.transferBusinessType4Distributor(businessType,distributorMark),XbbRefTypeEnum.ORDER_OUTSTOCK.getCode())){
                // 出库发货单 物流追踪关闭隐藏图标
                CompanyConfigEntity companyConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.LOGISTICS_TRACKING.getAlias(), corpid);
                if (Objects.isNull(companyConfig) || !Objects.equals(companyConfig.getConfigValue(),BasicConstant.ONE.toString())){
                    formDataGetVO.getData().put("LogisticsTrackingShow", BasicConstant.ZERO);
                }else {
                    formDataGetVO.getData().put("LogisticsTrackingShow", BasicConstant.ONE);
                }
            }
//            formDataGetAnalysisDataHelp.redPaymentShowHandle(formDataGetVO);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataGetVO;
    }

    /**
     * Description: 移动端detail
     *
     * @param formDataGetDTO
     * @return MobileFormCommonDetailVO
     * @throws XbbException
     * @author 刘阳
     * @date 2019/6/28 8:33 PM
     * @version v4.2.0.3
     * @update 2019/8/28 下午 by zcp 优化就地try catch：内部throw后，在调用方法的地方进行catch处理即可
     * @since v1.0
     */
    @Override
    public MobileFormCommonDetailVO getMoblieDetail(FormDataGetDTO formDataGetDTO) throws XbbException {
        BusinessDetailTopInfoService businessDetailTopInfoService = businessDetailTopInfoMap.get(formDataGetDTO.getBusinessType());
        if (Objects.nonNull(businessDetailTopInfoService) && !Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), formDataGetDTO.getDistributorMark())) {
            FormDataDetailDTO formDataDetailDTO = new FormDataDetailDTO();
            BeanUtil.copyProperties(formDataGetDTO, formDataDetailDTO);
            return businessDetailTopInfoService.getMobileDetail(formDataDetailDTO);
        }
        if ( Objects.equals(formDataGetDTO.getBusinessType(), XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode()) ) {
            return paymentBalanceService.getMoblieDetail(formDataGetDTO);
        }
        if ( Objects.equals(formDataGetDTO.getBusinessType(), XbbRefTypeEnum.PREPAY_BALANCE.getCode()) ) {
            return payBalanceService.getMoblieDetail(formDataGetDTO);
        }
        if ( Objects.equals(formDataGetDTO.getBusinessType(), XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode())
        || Objects.equals(formDataGetDTO.getBusinessType(), XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode())) {
            return marketingManagementService.getMoblieDetail(formDataGetDTO);
        }
        if ( Objects.equals(formDataGetDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) ) {
            // 产品编辑的时候一定要传父产品的id
            PaasFormDataEntityExt productEntity = saasGetHelp.getFormData(formDataGetDTO.getDataId(), formDataGetDTO.getCorpid(), XbbRefTypeEnum.PRODUCT.getCode());
            if ( productEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            JSONObject productData = productEntity.getData();
            Long parentId = productData.getLong(ProductEnum.PARENT_ID.getAttr());
            if ( !Objects.equals(parentId, 0L) ) {
                formDataGetDTO.setDataId(parentId);
            }
        }
        MobileFormCommonDetailVO mobileFormCommonDetailVO = new MobileFormCommonDetailVO();
        try {
            String userId = formDataGetDTO.getUserId();
            String corpid = formDataGetDTO.getCorpid();
            Integer saasMark = formDataGetDTO.getSaasMark();
            Long dataId = formDataGetDTO.getDataId();
            PaasFormDataEntityExt paasFormDataEntityExt;
            Integer distributorMark = formDataGetDTO.getDistributorMark();
            if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                Integer businessType = XbbRefTypeEnum.transferBusinessType4Distributor(formDataGetDTO.getBusinessType(), distributorMark);
                formDataGetDTO.setBusinessType(businessType);
                formDataGetDTO.setSubBusinessType(businessType);
            }
            Integer businessType = formDataGetDTO.getBusinessType();
            Integer subBusinessType = formDataGetDTO.getSubBusinessType();
            // 查看权限校验
            VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO();
            BeanUtil.copyProperties(formDataGetDTO, verifyViewPermissionDTO);
            ProPermissionHelp.verifyQueryPermission(verifyViewPermissionDTO);
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
            boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
            FieldAttrEntity labelField = null;
            HandlerExplainDTO handlerExplainDTO;
            if ( Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) ) {
                if (sheetFlag) {
                    paasFormDataEntityExt = proGetHelp.getByKey(dataId, sheetTypeEnum.getXbbRefTypeEnum().getCode(), SaasMarkEnum.SAAS.getCode(), corpid);
                } else {
                    paasFormDataEntityExt = proGetHelp.getByKey(dataId,  businessType, SaasMarkEnum.SAAS.getCode(), corpid);
                }
                paasFormDataEntityExt.setSaasMark(saasMark);
                handlerExplainDTO = initHandlerExplainDto(formDataGetDTO, paasFormDataEntityExt);
                // 数据权限判断
                verifyViewPermissionDTO.setPaasFormDataEntityExt(paasFormDataEntityExt);
                boolean hasDataPermission = commonPermissionHelp.checkViewPermission(verifyViewPermissionDTO);
                if (!Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_RECYCLE.getCode()) && !hasDataPermission) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                }

            } else {
                // 没有saasMark标志的，现在全按paas应用来处理
                paasFormDataEntityExt = paasFormDataModel.getByKey(dataId, corpid);
                paasFormDataEntityExt.setSaasMark(saasMark);
                handlerExplainDTO = initHandlerExplainDto(formDataGetDTO, paasFormDataEntityExt);
                // 数据权限判断
                verifyViewPermissionDTO.setPaasFormDataEntityExt(paasFormDataEntityExt);
                boolean hasDataPermission = commonPermissionHelp.checkViewPermission(verifyViewPermissionDTO);
                if (!hasDataPermission) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                }
            }
            commonPermissionHelp.removeConvertedData(paasFormDataEntityExt.getData());
            if ( paasFormDataEntityExt == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            } else if ( Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel()) ) {
                if ( Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_DUPLICATE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_RECYCLE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_DUPLICATE.getCode())) {
                    // 回收站的del为1
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
            }
            // 判断菜单和应用是否启用
            if (sheetFlag || Objects.equals(businessType, XbbRefTypeEnum.PAY_PLAN.getCode())) {
                validateAppAndMenuParentMenu(paasFormDataEntityExt.getAppId(), paasFormDataEntityExt.getMenuId(), corpid);
            } else {
                validateAppAndMenu(paasFormDataEntityExt.getAppId(), paasFormDataEntityExt.getMenuId(), corpid);
            }
            //审批中数据不让看，直接报错，目前这样处理，后续优化为可见，但没有任何操作权限
            if ( FlowStatusEnum.inApproval(paasFormDataEntityExt.getFlowStatus()) ) {
                throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200023);
            }

            Long formId = paasFormDataEntityExt.getFormId();
            formDataGetDTO.setFormId(formId);
            if ( Objects.equals(formDataGetDTO.getPlatform(), StringConstant.PLATFORM_DINGTALK) ) {
                if (RedundantTemplateTypeEnum.isMultiTemplate(businessType)) {
                    PaasFormEntityExt paasFormEntity = paasFormModel.getByKey(formId, corpid);
                    if ( Objects.equals(paasFormEntity.getEnable(), 0) || Objects.equals(paasFormEntity.getDel(), 1) ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                    }
                    List<PaasFormEntityExt> formList = new ArrayList<>();
                    formList.add(paasFormEntity);
                    paasFormService.removeByPermission(formList, formDataGetDTO.getLoginUser());
                    if ( formList.isEmpty() ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                    }
                }
            }

            PaasFormEntityExt paasFormEntity = paasFormModel.getByKey(formId, corpid);
            if ( paasFormEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            } else {
                //预防前端传错，根据form重置distributorMark
                distributorMark = paasFormEntity.getDistributorMark();
                businessType = XbbRefTypeEnum.transferBusinessType4Distributor(businessType, distributorMark);
                formDataGetDTO.setDistributorMark(distributorMark);
            }
            // fix: 20682 【成功部】移动端周报统计数据没出来，电脑上正常
            if ( Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), businessType) ) {
                subBusinessType = paasFormEntity.getBusinessType();
            }
            String creatorId = paasFormDataEntityExt.getCreatorId();
            List<LinkListPojo> linkList = JSON.parseArray(paasFormEntity.getAssociationList(), LinkListPojo.class);
            List<FieldAttrEntity> explainList = handlerExplainDTO.getExplainList();
            JSONObject ownerAndCoUser = handlerExplainDTO.getOwnerAndCoUser();
            Map<String, UserEntity> userMap = handlerExplainDTO.getUserMap();
            if (sheetFlag) {
                //如果是回/付款单，则根据数据data内的回/付款单类型重置sheetTypeEnum（前端传过来的businessType可能没有详细区分哪种类型回/付款单）
                sheetTypeEnum = fundHelp.getSheetTypeEnumByData(sheetTypeEnum, paasFormDataEntityExt.getData());
                fundHelp.handlePaymentSheet(false, sheetTypeEnum, explainList, corpid, distributorMark);
            }
            handlerExplainDTO.setCreatorId(creatorId);
            // ---- 获取用户和部门容器start
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(formDataGetDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(explainList);
//            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
//            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
//            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();

            Map<String, DepartmentEntity> departmentMap = commonHelp.getDepMap(userAndDepartmentGetDTO);

            handlerExplainDTO.setPaasFormEntityExt(paasFormEntity);
            handlerExplainDTO.setFormData(paasFormDataEntityExt.getData());
            HandlerExplainVO handlerExplainVO = formDataFormExplainHandleName.handleExplain(handlerExplainDTO);
            if ( handlerExplainVO == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            List<FieldAttrEntity> headList = handlerExplainVO.getHeadList();
            // 获取字段解释信息，并且过滤不可见字段 end
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(headList.size());
            // 将字段放入字段容器
            for ( FieldAttrEntity fieldAttrEntity : headList ) {
                //顺便查询出标签字段
                if(Objects.equals(fieldAttrEntity.getFieldType(),FieldTypeEnum.LABEL.getType())){
                    labelField = fieldAttrEntity;
                }
                explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
            }
            //将采购合同中应收、未收与采购金额可见权限一致
            if (Objects.equals(businessType,XbbRefTypeEnum.PURCHASE.getCode()) && explainMap.containsKey(PurchaseEnum.TOTAL_MONEY.getAttr())){
                VisibleRulePoJo visibleRulePoJo = explainMap.get(PurchaseEnum.TOTAL_MONEY.getAttr()).getVisibleScopeRule();
                Integer visibleScopeEnable = explainMap.get(PurchaseEnum.TOTAL_MONEY.getAttr()).getVisibleScopeEnable();
                Integer visible = explainMap.get(PurchaseEnum.TOTAL_MONEY.getAttr()).getVisible();
                if(Objects.equals(visibleScopeEnable,BasicConstant.ONE)){
                    //处理实付金额
                    FieldAttrEntity fieldAttrEntity = explainMap.get(PurchaseEnum.FINISH_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(PurchaseEnum.FINISH_AMOUNT.getAttr(), fieldAttrEntity);
                    }
                    //处理未付金额
                    fieldAttrEntity = explainMap.get(PurchaseEnum.UN_FINISH_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(PurchaseEnum.UN_FINISH_AMOUNT.getAttr(), fieldAttrEntity);
                    }
                    //处理坏账金额
                    fieldAttrEntity = explainMap.get(PurchaseEnum.BAD_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(PurchaseEnum.BAD_AMOUNT.getAttr(), fieldAttrEntity);
                    }
                }
            }
            //将合同订单中应收、未收与合同金额可见权限一致
            if (Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode()) && explainMap.containsKey(ContractEnum.AMOUNT.getAttr())){
                VisibleRulePoJo visibleRulePoJo = explainMap.get(ContractEnum.AMOUNT.getAttr()).getVisibleScopeRule();
                Integer visibleScopeEnable = explainMap.get(ContractEnum.AMOUNT.getAttr()).getVisibleScopeEnable();
                Integer visible = explainMap.get(ContractEnum.AMOUNT.getAttr()).getVisible();
                if (Objects.equals(visibleScopeEnable,BasicConstant.ONE)){
                    //处理实付金额
                    FieldAttrEntity fieldAttrEntity = explainMap.get(ContractEnum.FINISH_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(ContractEnum.FINISH_AMOUNT.getAttr(),fieldAttrEntity);
                    }
                    //处理未付金额
                    fieldAttrEntity = explainMap.get(ContractEnum.UN_FINISH_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(ContractEnum.UN_FINISH_AMOUNT.getAttr(),fieldAttrEntity);
                    }
                    //处理坏账金额
                    fieldAttrEntity = explainMap.get(ContractEnum.BAD_AMOUNT.getAttr());
                    if (Objects.nonNull(fieldAttrEntity)) {
                        fieldAttrEntity.setVisible(visible);
                        fieldAttrEntity.setVisibleScopeEnable(visibleScopeEnable);
                        fieldAttrEntity.setVisibleScopeRule(visibleRulePoJo);
                        explainMap.put(ContractEnum.BAD_AMOUNT.getAttr(), fieldAttrEntity);
                    }
                }
            }
            JSONObject data = paasFormDataEntityExt.getData();
            // 设置系统字段
            // 设置创建者
            data.put(FieldTypeEnum.ADDTIME.getAlias(), paasFormDataEntityExt.getAddTime());
            data.put(FieldTypeEnum.UPDATETIME.getAlias(), paasFormDataEntityExt.getUpdateTime());
            data.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEntityExt.getSerialNo());
            data.put(FieldTypeEnum.CREATORID.getAlias(), creatorId);
            data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEntityExt.getDepartmentId());

            //  获取用户和部门容器 解析paas的特殊数据 end
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            BeanUtil.copyProperties(formDataGetDTO, parseSingleRowDataDTO);
            parseSingleRowDataDTO.setDataJsonObject(data);
            parseSingleRowDataDTO.setExplainMap(explainMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            // 解析数据
            ParseSingleRowDataVO parseSingleRowDataVO = formDataGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
            if ( Objects.isNull(parseSingleRowDataVO) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
            }
            LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
            linkResultDataVO = linkResultDataVO == null ? new LinkResultDataVO() : linkResultDataVO;
            linkResultDataVO.setUserMap(userMap);
            linkResultDataVO.setDepartmentMap(departmentMap);
            data = parseSingleRowDataVO.getResult();
//            if ( !linkResultDataVO.getLinkData().isEmpty() && !linkResultDataVO.getLinkDataSet().isEmpty() ) {
//                linkResultDataVO.setData(data);
//                linkResultDataVO.setExplainMap(explainMap);
//                linkResultDataVO.setExplainList(headList);
//                data = formDataLinkDataGetServiceImpl.formDataLinkDataGet(formDataGetDTO, linkResultDataVO);
//            }
            // 处理关联数据逻辑 end
            List<DetailTabPojo> tabList;
            List<DetailTabPojo> tabPojoList = new ArrayList<>();
            List<PaasFormDataEntityExt> childDataList;

            FormDataDetailDTO formDataDetailDTO = new FormDataDetailDTO();
            BeanUtil.copyProperties(formDataGetDTO, formDataDetailDTO);

            UserVO loginUser = formDataGetDTO.getLoginUser();
            HandelDetailPojo handelDetailPojo = new HandelDetailPojo(distributorMark, businessType, loginUser, paasFormDataEntityExt, tabPojoList);
            // 移动端SaaS详情页额外展示信息
            if ( Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode()) ) {
                if ( Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) ) {
                    BoolQueryBuilder boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                    boolQueryBuilder.filter(termQuery(ProductEnum.getEsAttr4Keyword(ProductEnum.PARENT_ID), dataId));
                    boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                    List<PaasFormDataEntityExt> childList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, boolQueryBuilder, PaasFormDataEntityExt.class, Collections.singletonList(ProductEnum.getAttrConnectData(ProductEnum.STOCK)));
                    Double totalStock = 0D;
                    for ( PaasFormDataEntityExt entityExt : childList ) {
                        JSONObject jsonObject = entityExt.getData();
                        String attr = ProductEnum.STOCK.getAttr();
                        Double stock = jsonObject.containsKey(attr) ? jsonObject.getDouble(attr) : 0D;
                        totalStock += stock;
                    }
                    data.put(ProductEnum.STOCK.getAttr(), totalStock);
                    HashSet<Long> childPromotionProduct = marketingHelp.getChildPromotionProduct(dataId, corpid);
                    data.put(SelectProductEnum.DISCOUNT.getSaasAttr(), BasicConstant.ZERO);
                    if (CollectionUtils.isNotEmpty(childPromotionProduct)) {
                        data.put(SelectProductEnum.DISCOUNT.getSaasAttr(), BasicConstant.ONE);
                    }
                }
                List<MobileDetailMoneyItemPojo> moneyInfoList;
                if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode()) ) {
                    //工作报告业绩数据查询修改为工作报告提交人
                    moneyInfoList = mobileDetailService.getMobileDetailMoneyInfo(null, corpid, creatorId, businessType, subBusinessType, dataId, data, explainMap, loginUser);
                } else {
                    moneyInfoList = mobileDetailService.getMobileDetailMoneyInfo(distributorMark, corpid, userId, businessType, subBusinessType, dataId, data, explainMap, loginUser);
                }
                mobileFormCommonDetailVO.setMoneyInfo(moneyInfoList);
                JSONArray bottomBlockInfo = mobileDetailService.getBottomBlockInfo(corpid, userId, businessType, dataId, data, explainMap, paasFormDataEntityExt, formDataGetDTO);
                mobileFormCommonDetailVO.setBottomBlockInfo(bottomBlockInfo);
//                MobileDetailSpecialInfoPojo specialInfoPojo = mobileDetailService.getMobileDetailSpecialInfo(paymentSheetTypeEnum, corpid, userId, businessType, dataId, data, explainMap, paasFormDataEntityExt.getFlowStatus());
//                MobileDetailSpecialInfoPojo specialInfoPojo = mobileDetailService.getMobileDetailSpecialInfo(corpid, userId, businessType, dataId, data, explainMap, paasFormDataEntityExt.getFlowStatus());
                MobileDetailSpecialInfoPojo specialInfoPojo = mobileDetailService.getMobileDetailSpecialInfo(sheetTypeEnum,corpid, formDataGetDTO.getLoginUser(), businessType,paasFormDataEntityExt,explainMap);
                //判断老搜客能否使用
                SearchCustomerCompanyEntity byCorpid = searchCustomerCompanyModel.getByCorpid(formDataDetailDTO.getCorpid(), SoukeMealEnum.SOUKE.getType());
                if (Objects.nonNull(byCorpid) && byCorpid.getExtraExpiry() > DateUtil.getInt()){
                    mobileFormCommonDetailVO.setIsBusiness(1);
                }
                //判断工商查询能否使用
                if (fineClueHelp.isFineClueByCorpid(corpid, businessType, distributorMark)) {
                    mobileFormCommonDetailVO.setIsFineClue(1);
                }
                //详情页icon展示 有新搜客/工商查询优先跳到精线索的，只有老搜客跳老搜客的
                try {
                    // 只在客户模板中展示
                    if ( Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType) ) {
                        //搜客/工商查询老用户
                        String pid = fineClueHelp.getPidByCompanyName(corpid, paasFormDataEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr()) ,formDataDetailDTO.getPlatform());
                        if (Objects.nonNull(pid)) {
                            Map<String, Object> operation = specialInfoPojo.getOperation();
                            operation.put("pid", pid);
                            specialInfoPojo.setOperation(operation);
                        } else {
                            // saas头部栗子详情页(开启搜客或者工商后提供)
                            proDetailHandlerHelp.handelDetailClue(specialInfoPojo, paasFormDataEntityExt);
                        }
                    } else if (fineClueHelp.hasBusinessSearch(businessType)) {
                        // 搜客/工商查询用户
                        String pid = fineClueHelp.getPidByCompanyName(corpid, paasFormDataEntityExt.getData().getString(ManagementBaseEnum.NAME.getAttr()) ,formDataDetailDTO.getPlatform());
                        if (Objects.nonNull(pid)) {
                            Map<String, Object> operation = specialInfoPojo.getOperation();
                            operation.put("pid", pid);
                            specialInfoPojo.setOperation(operation);
                        }
                    }
                } catch (Exception e) {
                    LOG.info("工商查询没有查询到该公司");
                }
                mobileFormCommonDetailVO.setRightSpecialInfo(specialInfoPojo);
                PaasFormEntityExt paasFormEntityExt;
                paasFormEntityExt = paasFormEntity;

                // 详情特殊返回字段
                proDetailHandlerHelp.handleDetailSpecialField(data, paasFormDataEntityExt.getId(), businessType, corpid, explainMap, formDataGetDTO.getFormId(), handlerExplainDTO);
                // 详情特殊序列化解释
                proDetailHandlerHelp.handleDetailSpecialExplain(data, headList, businessType, formDataGetDTO.getPlatform(), corpid, formDataGetDTO.getFormId());
                FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
                BeanUtil.copyProperties(formDataGetDTO, formatExplainDTO);
                formatExplainDTO.setExplainList(headList);
                formatExplainDTO.setDataEntity(paasFormDataEntityExt);
                formatExplainDTO.setResult(data);
                // 编辑时saas字段显示特殊逻辑
                saasGetHelp.formatExplain(formatExplainDTO);
                headList = formatExplainDTO.getExplainList();
                SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
                BeanUtil.copyProperties(formDataGetDTO, saasAnalysisDataDTO);
                if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode()) ) {
                    //工作报告查询修改为工作报告提交人
                    saasAnalysisDataDTO.setUserId(creatorId);
                }
                //公海池特殊处理 负责人->前负责人
                Integer publicFlag = 0;
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                    publicFlag = getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), 0);
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                    publicFlag = getIntegerOrDefaultFromFormData(data, ClueEnum.IS_PUBLIC.getAttr(), 0);
                }
                Boolean isPublic = Objects.equals(publicFlag, 1);

                //跟进记录，供应商跟进记录，工作报告沿用老枚举，不走paas
                if ( Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode())
                    || Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_COMMUNICATE.getCode())) {
                    JSONArray summaryAttrArray = mobileDetailService.getShowAttrList(businessType);
                    List<SummaryDataPoJo> summaryList = ExplainUtil.getSummaryDataList(summaryAttrArray, data, explainMap, paasFormDataEntityExt);
                    mobileDetailService.transferKeyToShowValue(corpid, summaryList, businessType);
                    childDataList = mobileDetailService.handleSummarySpecialAttr(corpid, summaryList, businessType, data, dataId, paasFormDataEntityExt);
                    // 暂时在这里处理可见性
                    if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_COMMUNICATE.getCode())){
                        // 校验联系人字段是否可见
                        boolean contactAttrVisible = commonHelp.attrCanSee(CustomerCommunicateEnum.CONTACT_ARRAY.getAttr(), explainMap, handlerExplainDTO);
                        if(!contactAttrVisible){
                            summaryList.removeIf(summaryDataPoJo -> Objects.equals(summaryDataPoJo.getAttr(), CustomerCommunicateEnum.CONTACT_NAME_LINK_TEXT.getAttr()));
                        }
                    }
                    mobileFormCommonDetailVO.setSummaryList(summaryList);
                } else {
                    // saas特殊格式转换
                    saasGetHelp.formatData(saasAnalysisDataDTO, data);
                    if (Objects.equals(XbbRefTypeEnum.WAREHOUSE.getCode(), businessType)) {
                        Map<String, Object> param = new HashMap<>(16);
                        param.put("corpid", corpid);
                        param.put("del", 0);
                        param.put("type", 0);
                        param.put("dataId", dataId);
                        List<WarehouseUserEntity> warehouseUserEntities = warehouseUserModel.findEntitys(param);
                        List<ReturnUserAndDepartmentPojo> returnUserAndDepartmentPojos = new ArrayList<>();
                        for (WarehouseUserEntity warehouseUserEntity : warehouseUserEntities) {
                            ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                            returnUserAndDepartmentPojo.setId(warehouseUserEntity.getRelationId());
                            returnUserAndDepartmentPojo.setName(warehouseUserEntity.getRelationName());
                            returnUserAndDepartmentPojos.add(returnUserAndDepartmentPojo);
                        }
                        JSONArray userArray = JSON.parseArray(JSON.toJSONString(returnUserAndDepartmentPojos));
                        data.put(WarehouseEnum.MANAGER_ID.getAttr(), userArray);
                    }
                    if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                        // 客户最后跟进时间
                        FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
                        formConfigGetDTO.setCorpid(paasFormDataEntityExt.getCorpid());
                        formConfigGetDTO.setBusinessType(businessType);
                        formConfigGetDTO.setFormId(paasFormDataEntityExt.getFormId());
                        Map<String, String> lastConnectTimeMap = formDataListAnalysisDataHelp.lastConnectTime(formConfigGetDTO);
                        String lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.CUSTOMER_LAST_CONNECT_TIME.getConfig());
                        if(Objects.equals(lastConnectTime, "0")){
                            String time = data.getString(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr());
                            data.put(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr(), DateTimeUtil.getInt(time, DateTimeUtil.SDFYMDHM));
                        }
                    }
                    if(Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
                        // 线索最后跟进时间
                        FormConfigGetDTO formConfigGetDTO = new FormConfigGetDTO();
                        formConfigGetDTO.setCorpid(paasFormDataEntityExt.getCorpid());
                        formConfigGetDTO.setBusinessType(businessType);
                        formConfigGetDTO.setFormId(paasFormDataEntityExt.getFormId());
                        Map<String, String> lastConnectTimeMap = formDataListAnalysisDataHelp.lastConnectTime(formConfigGetDTO);
                        String lastConnectTime = lastConnectTimeMap.get(FormConfigEnum.CLUE_LAST_CONNECT_TIME.getConfig());
                        if(Objects.equals(lastConnectTime, "0")){
                            String time = data.getString(ClueEnum.LAST_CONNECT_TIME.getAttr());
                            data.put(ClueEnum.LAST_CONNECT_TIME.getAttr(), DateTimeUtil.getInt(time, DateTimeUtil.SDFYMDHM));
                        }
                    }
                    // 解析摘要
                    List<SummaryDataPoJo> summaryList = ExplainUtil.getSpecialSummaryList(paasFormEntityExt.getSummaryList(), data, explainMap, paasFormDataEntityExt);
                    if (isPublic) {
                        mobileDetailService.handelPublic(corpid, summaryList, dataId, businessType);
                    }
                    //访客计划延期原因，延期备注
                    if ( Objects.equals(businessType, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode()) ) {
                        mobileDetailService.handelCommunicatePlan(corpid, data, summaryList, paasFormDataEntityExt);
                    }
                    childDataList = mobileDetailService.handleSummarySpecialAttr(corpid, summaryList, businessType, data, dataId, paasFormDataEntityExt);
                    mobileDetailService.specialTransferKeyToShowValue(corpid, summaryList, businessType, data, paasFormDataEntityExt.getFormId());
                    // APP客户详情显示即将退回公海原因
                    if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                        Map<Long,String> publicTagMap = tagLinkModel.getPublicTag(corpid, Arrays.asList(dataId));
                        if (Objects.nonNull(publicTagMap) && publicTagMap.containsKey(dataId)){
                            SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
                            summaryDataPoJo.setAttr(TagEnum.TAG_RETURN_PUBLIC.getAttr());
                            summaryDataPoJo.setAttrName(I18nMessageUtil.getMessage(StringConstant.RETURN_PUBLIC));
                            String memo = publicTagMap.get(dataId);
                            summaryDataPoJo.setValue(Arrays.asList(memo));
                            summaryList.add(summaryDataPoJo);
                        }
                        //客户详情 转移标签
                        Map<Long,String> transferTagMap = tagLinkModel.getTransferTag(corpid, Arrays.asList(dataId),XbbRefTypeEnum.CUSTOMER_TRANSFER.getCode());
                        if (Objects.nonNull(transferTagMap) && transferTagMap.containsKey(dataId)){
                            SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
                            summaryDataPoJo.setAttr(TagEnum.TAG_TRANSFER_PUBLIC_CUSTOMER.getAttr());
                            summaryDataPoJo.setAttrName(I18nMessageUtil.getMessage(StringConstant.TRANSFER_PUBLIC));
                            String memo = transferTagMap.get(dataId);
                            summaryDataPoJo.setValue(Arrays.asList(memo));
                            summaryList.add(summaryDataPoJo);
                        }

                    } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                        Map<Long,String> publicTagMap = tagLinkModel.getCluePublicTag(corpid, Arrays.asList(dataId));
                        if (Objects.nonNull(publicTagMap) && publicTagMap.containsKey(dataId)){
                            SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
                            summaryDataPoJo.setAttr(TagEnum.TAG_RETURN_PUBLIC_CLUE.getAttr());
                            summaryDataPoJo.setAttrName(I18nMessageUtil.getMessage(StringConstant.RETURN_PUBLIC));
                            String memo = publicTagMap.get(dataId);
                            summaryDataPoJo.setValue(Arrays.asList(memo));
                            summaryList.add(summaryDataPoJo);
                        }
                        //线索详情 转移标签
                        Map<Long,String> transferTagMap = tagLinkModel.getTransferTag(corpid, Arrays.asList(dataId),XbbRefTypeEnum.CLUE_TRANSFER.getCode());
                        if (Objects.nonNull(transferTagMap) && transferTagMap.containsKey(dataId)){
                            SummaryDataPoJo summaryDataPoJo = new SummaryDataPoJo();
                            summaryDataPoJo.setAttr(TagEnum.TAG_TRANSFER_PUBLIC_CLUE.getAttr());
                            summaryDataPoJo.setAttrName(I18nMessageUtil.getMessage(StringConstant.TRANSFER_PUBLIC));
                            String memo = transferTagMap.get(dataId);
                            summaryDataPoJo.setValue(Arrays.asList(memo));
                            summaryList.add(summaryDataPoJo);
                        }
                    }
                    mobileFormCommonDetailVO.setSummaryList(summaryList);
                }
                // 解析标签
                List<SummaryDataPoJo> labelsList = ExplainUtil.getSpecialSummaryList(paasFormEntity.getLabelsList(), data, explainMap, paasFormDataEntityExt);
                if (isPublic) {
                    mobileDetailService.handelPublic(corpid, labelsList, dataId, businessType);
                }
                //访客计划延期的情况标签塞一个（访客计划状态）
                if ( Objects.equals(businessType, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode()) ) {
                    mobileDetailService.handleCommunicatePlan(labelsList, data);
                }
                //回款计划的要塞一个状态的标签
                if ( Objects.equals(businessType, XbbRefTypeEnum.PAYMENT_TASK.getCode()) ) {
                    mobileDetailService.handlePaymentTask(labelsList, data);
                }
                // 进行了退货退款的合同塞一个标签(退货合同)
                if ( Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
                    //是否包含红冲合同（即是否为退货合同）
                    Integer hasRed = data.getIntValue(ContractEnum.HAS_RED.getAttr());
                    if ( Objects.equals(hasRed, 1) ) {
                        SummaryDataPoJo dataPoJo = new SummaryDataPoJo();
                        String name = I18nMessageUtil.getMessage(I18nStringConstant.RETURN_CONTRACT);
                        dataPoJo.setAttr("");
                        dataPoJo.setType("red");
                        dataPoJo.setAttrName(name);
                        dataPoJo.setFieldType(3);
                        List<Object> objectList = new ArrayList<>();
                        Object obj = name;
                        objectList.add(obj);
                        dataPoJo.setValue(objectList);
                        labelsList.add(0, dataPoJo);
                    }
                }
                for ( SummaryDataPoJo item : labelsList ) {
                    if ( Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType) && Objects.equals(item.getAttr(), ProductEnum.COST.getAttr()) ) {
                        item.setValue(Collections.singletonList(productService.getCostBySummary(childDataList, corpid, dataId)));
                    }
                }
                // 参考上面的标题的思路，当未传值时，提供个空字符串
                for ( SummaryDataPoJo poJo : labelsList ) {
                    if ( poJo.getValue().size() == 0 ) {
                        List<Object> objects = new ArrayList<>();
                        objects.add("");
                        poJo.setValue(objects);
                    }
                }
                childDataList = mobileDetailService.handleSummarySpecialAttr(corpid, labelsList, businessType, data, dataId, paasFormDataEntityExt);
                // SaaS业务特殊处理，将数据字典的key值转成显示的value值
                mobileDetailService.specialTransferKeyToShowValue(corpid, labelsList, businessType, data, paasFormDataEntityExt.getFormId());
                Map<String, LabelPojo> nameToLabel = dealLabel(paasFormDataEntityExt, corpid, labelsList);
                for (SummaryDataPoJo summaryDataPoJo : labelsList) {
                    List<Object> list = summaryDataPoJo.getValue();
                    if (Objects.equals(summaryDataPoJo.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                        JSONArray tags = new JSONArray();
                        if (CollectionsUtil.isNotEmpty(list)) {
                            int size = list.size();
                            for (Object o : list) {
                                if (o instanceof JSONObject){
                                    JSONObject object1 = new JSONObject();
                                    object1.put("value", o);
                                    object1.put("type", "label");
                                    tags.add(object1);
                                } else {
                                    if (Objects.isNull(nameToLabel.get(o))) {
                                        continue;
                                    }
                                    JSONObject object1 = new JSONObject();
                                    object1.put("value", nameToLabel.get(o));
                                    object1.put("type", "label");
                                    tags.add(object1);
                                }
                            }
                        }

                        //个人标签tags展示
                        PersonLabelFindDTO personLabelFindDTO = new PersonLabelFindDTO(corpid, businessType, dataId, userId);
                        PersonLabelEntity personLabelEntity = personLabelService.findEntitys(personLabelFindDTO);
                        if (Objects.nonNull(personLabelEntity)) {
                            JSONArray labelNameArray = personLabelEntity.getLabelName();
                            if (labelNameArray !=null && labelNameArray.size() > 0) {
                                JSONObject object1 = new JSONObject();
                                object1.put("value", personLabelEntity);
                                object1.put("type", "personLabel");
                                tags.add(object1);
                            }
                        }
                        summaryDataPoJo.setValue(tags);
                        continue;
                    }
                }
                mobileFormCommonDetailVO.setLabelsList(labelsList);
                // 移动端工作报告详情页，标题特殊处理
                if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode()) ) {
                    Integer workReportType = getIntegerOrDefaultFromFormData(data, WorkReportFieldEnum.TYPE.getAttr(), 0);
                    WorkReportTypeEnum typeEnum = WorkReportTypeEnum.getByType(workReportType);
                    if ( typeEnum != null ) {
                        FormTitlePoJo formTitlePoJo = new FormTitlePoJo();
                        formTitlePoJo.setAttr(WorkReportFieldEnum.TYPE.getAttr());
                        String value = "";
                        if ( userMap.get(creatorId) != null && userMap.get(creatorId).getName() != null ) {
                            value = userMap.get(creatorId).getName() + I18nMessageUtil.getMessage(CommonConstant.OF) + typeEnum.getName();
                        } else {
                            value = typeEnum.getName();
                        }
                        formTitlePoJo.setValue(Arrays.asList(value));
                        mobileFormCommonDetailVO.setTitleList(Arrays.asList(formTitlePoJo));
                    }
                } else {
                    // 解析标题
                    List<FormTitlePoJo> formTitleList = ExplainUtil.getSpecailFormTitle(JSONArray.parseArray(paasFormEntity.getCustomTitle()), explainMap, data, headList, paasFormDataEntityExt);
                    for ( FormTitlePoJo formTitlePoJo : formTitleList ) {
                        if ( Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType) && Objects.equals(formTitlePoJo.getAttr(), ProductEnum.COST.getAttr()) ) {
                            formTitlePoJo.setValue(Collections.singletonList(productService.getCostBySummary(childDataList, corpid, dataId)));
                        } else if ( Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType) && Objects.equals(formTitlePoJo.getAttr(), ProductEnum.PRICE.getAttr()) ) {
                            formTitlePoJo.setValue(Collections.singletonList(productService.getPriceBySummary(childDataList, corpid, dataId)));
                        }
                    }
                    //如果value为空赛个空值，方便前端拼接字段
                    for ( FormTitlePoJo poJo : formTitleList ) {
                        if ( poJo.getValue().size() == 0 ) {
                            if ( poJo.getContent() != null ) {
                                List<Object> objects = new ArrayList<>();
                                objects.add(poJo.getContent());
                                poJo.setValue(objects);
                            } else {
                                List<Object> objects = new ArrayList<>();
                                objects.add("");
                                poJo.setValue(objects);
                            }
                        }
                    }
                    mobileFormCommonDetailVO.setTitleList(formTitleList);
                }
                // saas详情tab
                Integer feeType = packageHelp.getFeeType(corpid);
                proDetailHandlerHelp.handelDetailTab(handelDetailPojo, PlatFormEnum.DINGTALK, explainMap, feeType);
                handlerExplainDTO.setOwnerId(ownerAndCoUser.getJSONArray(FieldTypeEnum.OWNERID.getAlias()).toJavaList(String.class));
                handlerExplainDTO.setCoUserId(ownerAndCoUser.getJSONArray(FieldTypeEnum.COUSERID.getAlias()).toJavaList(String.class));
                handlerExplainVO.setHandlerExplainDTO(handlerExplainDTO);
                if ( Objects.nonNull(businessType) && XbbRefTypeEnum.WORK_REPORT.getCode() != businessType ) {
                    tabList = ExplainUtil.getFieldListIncludeSubForm(handlerExplainVO, handlerExplainDTO);
                    Integer finalBusinessType = businessType;
                    tabList.removeIf(item -> Objects.equals(finalBusinessType, XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(item.getAttr(),ProductEnum.STOCK_NOTIFY.getAttr()));
                } else {
                    // 获取子表单tab栏
                    tabList = ExplainUtil.getSubFormToTabWorkReport(handlerExplainVO, handlerExplainDTO);
                }
                // saas特殊返回字段，放在一个对象中
                FormDataGetVO formDataGetVO = new FormDataGetVO();
                saasGetHelp.formatSaasAttrToReturn(formDataGetVO, formDataGetDTO, data);
                mobileFormCommonDetailVO.setSaasObj(formDataGetVO.getSaasObj());
                // 解析saas pro的特殊数据，包括下拉框的回显
                PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
                List<PaasFormDataEntityExt> formDataEsEntities = new ArrayList<>();
                PaasFormDataEntityExt paasFormDataEsEntity = new PaasFormDataEntityExt();
                BeanUtil.copyProperties(paasFormDataEntityExt, paasFormDataEsEntity);
                paasFormDataEsEntity.setData(data);
                formDataEsEntities.add(paasFormDataEsEntity);
                paasFormDataEsListVO.setBusinessType(businessType);
                paasFormDataEsListVO.setPaasFormDataESList(formDataEsEntities);
                saasListHelp.analysisSaasDataList(paasFormDataEsListVO, explainMap);
                formDataEsEntities = paasFormDataEsListVO.getPaasFormDataESList();
                data = formDataEsEntities.get(0).getData();
                if (sheetFlag) {
                    JSONArray amountDetail = getAmountDetail4exist(sheetTypeEnum, parseSingleRowDataDTO, corpid, dataId, paasFormDataEntityExt);
                    mobileFormCommonDetailVO.setAmountDetail(amountDetail);
                }
            } else {
                // 渲染业务规则
                for ( PaasDetailTabEnum paasDetailTabEnum : PaasDetailTabEnum.values() ) {
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(paasDetailTabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(paasDetailTabEnum.getAnEnum().getKey());
                    if(!Objects.equals(PlatFormEnum.WEB,paasDetailTabEnum.getPlatform())){
                        tabPojoList.add(detailTabPojo);
                    }
                }
                // 获取子表单tab栏
                handlerExplainVO.setHandlerExplainDTO(handlerExplainDTO);
                tabList = ExplainUtil.getFieldListIncludeSubForm(handlerExplainVO, handlerExplainDTO);
                mobileFormCommonDetailVO.setRightSpecialInfo(new MobileDetailSpecialInfoPojo());

                JSONArray bottomBlockInfo = mobileDetailService.getPaasBottomBlockInfo(corpid, userId, dataId, data, explainMap, paasFormDataEntityExt, formDataGetDTO);
                mobileFormCommonDetailVO.setBottomBlockInfo(bottomBlockInfo);

                // 解析摘要
                paasFormDataEntityExt.setData(data);
                List<SummaryDataPoJo> summaryList = paasFormHelp.getSummaryList(paasFormEntity, explainMap, paasFormDataEntityExt);
                mobileFormCommonDetailVO.setSummaryList(summaryList);
                // 解析标题
                List<FormTitlePoJo> formTitleList = ExplainUtil.getFormTitle(JSONArray.parseArray(paasFormEntity.getCustomTitle()), explainMap, data, headList, paasFormDataEntityExt);
                mobileFormCommonDetailVO.setTitleList(formTitleList);
                // 解析标签
                List<SummaryDataPoJo> labelsList = ExplainUtil.getSummaryList(paasFormEntity.getLabelsList(), data, explainMap, paasFormDataEntityExt);
//                formDataDetailDTO.setBusinessType(XbbRefTypeEnum.PAAS.getCode());
//                proDetailHandlerHelp.addEsignTab4Paas(formDataDetailDTO,paasFormDataEntityExt, labelsList);
                //仅详情页需要展示个人标签,对返回视图中标签进行特殊处理
                Integer finalBusinessType = businessType;
                labelsList.forEach(item->{
                    if ( Objects.equals(item.getFieldType(),FieldTypeEnum.LABEL.getType()) ) {
                        List<Object> objectLists = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        List<Object> objectList = item.getValue();
                        objectList.forEach(obj->{
                            JSONObject object = (JSONObject) obj;
                            Integer tabelType = object.getIntValue("tabelType");
                            if ( Objects.equals(tabelType,0) ) {
                                JSONObject jsonObject = new JSONObject();
                                jsonObject.put("value",object);
                                jsonObject.put("type","label");
                                objectLists.add(jsonObject);
                            }
                        });
                        //个人标签tags展示
                        PersonLabelFindDTO personLabelFindDTO = new PersonLabelFindDTO(corpid, finalBusinessType, dataId, userId);
                        PersonLabelEntity personLabelEntity = personLabelService.findEntitys(personLabelFindDTO);
                        if (Objects.nonNull(personLabelEntity)) {
                            JSONArray labelNameArray = personLabelEntity.getLabelName();
                            if (labelNameArray !=null && labelNameArray.size() > 0) {
                                JSONObject object = new JSONObject();
                                object.put("value", personLabelEntity);
                                object.put("type", "personLabel");
                                objectLists.add(object);
                            }
                        }
                        item.setValue(objectLists);
                    }
                });
                mobileFormCommonDetailVO.setLabelsList(labelsList);
            }

            tabPojoList.addAll(tabList);
            proDetailHandlerHelp.addEsignTab4Saas(formDataDetailDTO,paasFormDataEntityExt, tabPojoList);
            // 拼装关联列表的tab和按钮
            paasFormHelp.getLinkList(linkList, corpid);
            paasFormHelp.getLinkListTab(linkList, tabPojoList, formDataGetDTO.getLoginUser());
            cloudCodeHelp.setCloudCodeTab4Dingtalk(corpid, formDataGetDTO.getLoginUser().getDynamicPermSet(), formDataGetDTO.getAppId(), formId, businessType,  tabPojoList);

            // tab自定义排序
            tabPojoList = proDetailHandlerHelp.handleDetailTabSort(userId, corpid, formId, businessType, tabPojoList);
            //移动端去掉阶段历史
            tabPojoList.removeIf(e -> Objects.equals(DetailTabEnum.CUSTOMER_STAGE.getKey(), e.getKey()));

            //未开启工作流的公司不能查看审批记录
            boolean isOpenWorkflow = commonHelp.isOpenWorkFlow(corpid);
            if(!isOpenWorkflow){
                tabPojoList.removeIf(v -> Objects.equals(v.getAttr(), DetailTabEnum.APPROVAL_HISTORY.getKey()) || Objects.equals(v.getAttr(), DetailTabEnum.APPROVAL_PROCESS.getKey()));
            }

            mobileFormCommonDetailVO.setTabList(tabPojoList);

            /* ==================== 上部按钮权限 ==================== */
            // web 端详情权限在getDetail方法中
            if (Objects.equals(formDataGetDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && Objects.equals(PlatFormEnum.DINGTALK.getValue(), formDataGetDTO.getPlatform())) {
                // 设置移动端详情右上角操作
                FormDataGetVO formDataGetVO = new FormDataGetVO();
                formDataGetVO.setDistributorMark(distributorMark);
                mobileDetailService.handelMobileWorkFlow(formDataGetDTO.getLoginUser(), XbbRefTypeEnum.transferBusinessType4Distributor(businessType,formDataDetailDTO.getDistributorMark()), formDataGetVO, paasFormDataEntityExt);
                mobileFormCommonDetailVO.setTopPermissions(formDataGetVO.getTopPermissions());
                // SaaS移动端详情底部操作
                mobileFormCommonDetailVO.setDistributorMark(distributorMark);
                mobileFormCommonDetailVO.setBottomOperation(mobileDetailService.getMobileDetailBottomOperation(handelDetailPojo));
                proDetailHandlerHelp.setTagInDetail(mobileFormCommonDetailVO,businessType,data);
            } else if ( Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode()) ) {
                UserFormPermissionVO userFormPermissionVO = userService.getUserFormPermissionInternal(corpid,
                        formDataGetDTO.getUserId(), paasFormEntity.getAppId(), paasFormEntity.getMenuId());
                List<ButtonPojo> buttonPojoList = setDetailButtonPermission(userFormPermissionVO, formDataGetDTO.getPlatform(), DelEnum.NORMAL.getDel());
                proDetailHandlerHelp.addPaasEsignBtn(userFormPermissionVO, formDataDetailDTO,paasFormDataEntityExt, buttonPojoList);
                List<TopPermissionsPoJo> topPermissions = new ArrayList<>();
                buttonPojoList.forEach(item -> {
                    TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                    BeanUtil.copyProperties(item, topPermissionsPoJo);
                    topPermissionsPoJo.setBtnType(item.getAttr());
                    if ( Objects.equals(PlatFormEnum.DINGTALK.getValue(), formDataGetDTO.getPlatform()) && SaasButtonEnum.DEL.getAttr().equals(item.getAttr()) ) {
                        topPermissionsPoJo.setBtnType("delete");
                    }

                    topPermissions.add(topPermissionsPoJo);
                });
                mobileFormCommonDetailVO.setTopPermissions(topPermissions);
            }
            //顶部按钮权限过滤
            proDetailHandlerHelp.mobileRemoveEditButtom(formDataGetDTO, mobileFormCommonDetailVO.getTopPermissions(), explainMap, paasFormDataEntityExt);

            // web 端详情权限在getDetail方法中
            if ( CollectionsUtil.isNotEmpty(linkList)) {
                // 设置关联列表的按钮
                List<TopPermissionsPoJo> topPermissions = mobileFormCommonDetailVO.getTopPermissions();
                paasFormHelp.setMobileLinkListButton(topPermissions, linkList, formDataDetailDTO.getLoginUser());
                mobileFormCommonDetailVO.setTopPermissions(topPermissions);
            }
            List<TopPermissionsPoJo> topPermissions = mobileFormCommonDetailVO.getTopPermissions();
            cloudCodeHelp.setCloudCodeDetailButton4Dingtalk(corpid, formDataGetDTO.getLoginUser().getDynamicPermSet(), formDataGetDTO.getAppId(), formId, businessType, topPermissions);
            // 低代码按钮
            CustomButtonListDTO customButtonListDTO = new CustomButtonListDTO();
            customButtonListDTO.setBusinessType(formDataDetailDTO.getBusinessType());
            customButtonListDTO.setFormId(formId);
            customButtonListDTO.setSaasMark(formDataDetailDTO.getSaasMark());
            customButtonListDTO.setCorpid(formDataDetailDTO.getCorpid());
            customButtonListDTO.setLoginUser(formDataDetailDTO.getLoginUser());
            customButtonListDTO.setType(ButtonTypeEnum.DETAIL.getCode());
            CustomButtonListVO formCustomButtonListVO = customButtonService.listByPermission(customButtonListDTO);
            if (Objects.nonNull(formCustomButtonListVO) && CollectionsUtil.isNotEmpty(formCustomButtonListVO.getCustomButtonList())) {
                for (CustomButtonPojo item : formCustomButtonListVO.getCustomButtonList()) {
                    TopPermissionsPoJo buttonPojo = new TopPermissionsPoJo();
                    buttonPojo.setActionList(item.getActionList());
                    buttonPojo.setValue(item.getName());
                    buttonPojo.setAttr(PaasConstant.LOW_CODE+StringConstant.UNDER_LINE+item.getId());
                    buttonPojo.setBtnType(PaasConstant.LOW_CODE);
                    topPermissions.add(buttonPojo);
                }
            }
            //标签详情页快捷编辑
            String labelEditAttr = labelHelp.dealAppDetailLabelListLocation(formDataDetailDTO, mobileFormCommonDetailVO.getLabelsList(), paasFormDataEntityExt, labelField);
            if(labelEditAttr != null){
                mobileFormCommonDetailVO.setLabelEditAttr(labelEditAttr);
            }
            mobileFormCommonDetailVO.setTopPermissions(topPermissions);
            mobileFormCommonDetailVO.setPaasFormEntity(paasFormEntity);
            mobileFormCommonDetailVO.setData(data);
            //校验套餐类型
            Integer feeType = packageHelp.getFeeType(corpid);
            if (!Objects.equals(feeType,PackageTypeEnum.STANDARD.getType())){
                boolean hasOuterLinkShare = outerLinkModel.checkOuterLinkEnable(formId, OuterLinkTypeEnum.SHARE.getCode(), corpid);
                if (hasOuterLinkShare) {
                    mobileFormCommonDetailVO.setHasOuterLinkShare(BasicConstant.ONE);
                }
            }
            if ( Objects.nonNull(businessType) && Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                //默认非公海
                Integer isPublic = 0;
                if ( data.containsKey(CustomerManagementEnum.IS_PUBLIC.getAttr()) ) {
                    isPublic = data.getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr());
                }
                mobileFormCommonDetailVO.setIsPublic(isPublic);
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return mobileFormCommonDetailVO;
    }

    /**
     * 初始化HandlerExplainDTO,做一些基本操作
     *
     * @param formDataGetDTO
     * @param paasFormDataEntityExt
     * @return
     * @throws XbbException
     */
    private HandlerExplainDTO initHandlerExplainDto(FormDataGetDTO formDataGetDTO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException{
        PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(formDataGetDTO.getCorpid(), formDataGetDTO.getFormId(), formDataGetDTO.getBusinessType());
        paasFormDataEntityExt.setMenuId(paasFormExplainEntity.getMenuId());
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataGetDTO, handlerExplainDTO, false);
        Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        handlerExplainDTO.setExplainList(explainList);
        // 获取协同人和负责人
        JSONObject ownerAndCoUser = paasFormHelp.getOwnerIdAndCoUserId(handlerExplainDTO, formDataGetDTO.getSaasMark(),
                formDataGetDTO.getBusinessType(), formDataGetDTO.getSubBusinessType(), paasFormDataEntityExt, userMap);
        paasFormDataEntityExt.getData().putAll(ownerAndCoUser);
        handlerExplainDTO.setUserMap(userMap);
        handlerExplainDTO.setOwnerAndCoUser(ownerAndCoUser);
        return handlerExplainDTO;
    }



    private Map<String, LabelPojo> dealLabel(PaasFormDataEntityExt paasFormDataEntityExt, String corpid, List<SummaryDataPoJo> labelsList) {
        List<Object> list = new ArrayList<>();
        for (SummaryDataPoJo summaryDataPoJo : labelsList) {
            if (Objects.equals(summaryDataPoJo.getFieldType(), FieldTypeEnum.LABEL.getType())){
                list = summaryDataPoJo.getValue();
            }
        }
        Map<String, LabelPojo> nameToLabel = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (CollectionsUtil.isNotEmpty(list)){
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("formId", paasFormDataEntityExt.getFormId());
            param.put("appId", paasFormDataEntityExt.getAppId());
            param.put("del", DelEnum.NORMAL.getDel());
            List<LabelEntity> entitys = labelModel.findEntitys(param);
            entitys.forEach(item->nameToLabel.put(item.getName(), new LabelPojo(item.getId(),item.getColor(),item.getName())));
        }
        return nameToLabel;
    }

    @Override
    public FormDataDeleteVO delete(FormDataDeleteDTO formDataDeleteDTO) throws XbbException {
        FormDataDeleteVO formDataDeleteVO = new FormDataDeleteVO();
        String corpid = formDataDeleteDTO.getCorpid();
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataDeleteDTO.getFormId(), corpid);
        if ( Objects.isNull(paasFormEntityExt) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        PaasFormDataEntity paasFormDataEntity = paasFormDataModel.getByKey(formDataDeleteDTO.getDataId(), corpid);
        if ( Objects.isNull(paasFormDataEntity) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        try {
            paasFormDataModel.delete(formDataDeleteDTO.getDataId().intValue(), formDataDeleteDTO.getCorpid());
            formDataDeleteVO.setDataId(formDataDeleteDTO.getDataId());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库删除表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }

        // 记录日志
        String userId = formDataDeleteDTO.getUserId();
        String userName = formDataDeleteDTO.getLoginUserName();
        String formName = paasFormEntityExt.getName();
        String serialNo = paasFormDataEntity.getSerialNo();
        String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_FORM_DATA), userName, formName, serialNo);
        mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.PAAS_FORM_DATA, OperateTypeEnum.DELETE,
                formDataDeleteDTO.getDataId().toString(), serialNo, memo, formDataDeleteDTO.getHttpHeader());

        return formDataDeleteVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
//    @ConcurrentLock(businessType = HandleProductWayEnum.ADD)
    public FormDataAddVO add(FormDataAddDTO formDataSaveDTO) throws XbbException {
        FormDataAddVO formDataSaveVO;
        Integer businessType = formDataSaveDTO.getBusinessType();
        Integer saasMark = formDataSaveDTO.getSaasMark();
        try {
            String corpid = formDataSaveDTO.getCorpid();
            if(Objects.equals(formDataSaveDTO.getBusinessType(),XbbRefTypeEnum.RED_RECEIVABLES.getCode())){
                formDataSaveDTO.setBusinessType(XbbRefTypeEnum.PAYMENT.getCode());
            }
            if (!Objects.equals(formDataSaveDTO.getIsImport(), BasicConstant.ONE)) {
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                //非导入时判断数据量限制
                Integer oneStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.ONE_FORM_DATA_NUM, 1, xbbRefTypeEnum, formDataSaveDTO.getFormId());
                Integer allStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, 1);
                if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
                }

                if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
                }
            }
            if (Objects.equals(formDataSaveDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                // 经销商
                return distributorFormDataService.add(formDataSaveDTO);
            } else if (Objects.equals(formDataSaveDTO.getBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
                return priceSetService.add(formDataSaveDTO);
            }
            if (Objects.isNull(formDataSaveDTO.getDistributorMark())){
                PaasFormEntityExt paasFormEntityExt;
                if (Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode())) {
                    JSONObject typeObject = formDataSaveDTO.getDataList().getJSONObject(WorkReportFieldEnum.TYPE.getAttr());
                    Integer type = typeObject.getInteger("value");
                    WorkReportTypeEnum workReportTypeEnum = WorkReportTypeEnum.getByType(type);
                    if(Objects.isNull(workReportTypeEnum)){
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028 ,MessageConstant.ABNORMAL_PARAMETER, WorkReportDailyEnum.TYPE.getAttrName());
                    }
                    if (!Objects.equals(formDataSaveDTO.getSubBusinessType(), workReportTypeEnum.getBusinessType())){
                        formDataSaveDTO.setSubBusinessType(workReportTypeEnum.getBusinessType());
                    }
                    paasFormEntityExt = paasFormModel.getByBusinessType(formDataSaveDTO.getSubBusinessType(),corpid);
                    // 重新设置formId，获取正确解释
                    Long workReportFormId = Objects.nonNull(paasFormEntityExt) ? paasFormEntityExt.getId() : formDataSaveDTO.getFormId();
                    formDataSaveDTO.setFormId(workReportFormId);
                } else if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                    WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formDataSaveDTO.getFormId(), corpid);
                    if (Objects.isNull(workOrderFormEntityExt)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                    }
                    paasFormEntityExt = new PaasFormEntityExt(workOrderFormEntityExt.getCorpid(), workOrderFormEntityExt.getAppId(), workOrderFormEntityExt.getMenuId(),
                            workOrderFormEntityExt.getName(), SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode(), workOrderFormEntityExt.getEnable(),
                            workOrderFormEntityExt.getIsProcessForm(), workOrderFormEntityExt.getVerifyRule(), workOrderFormEntityExt.getDisableFieldAssign(), workOrderFormEntityExt.getFrontCache(),
                            workOrderFormEntityExt.getTitleType(), workOrderFormEntityExt.getCustomTitle(), workOrderFormEntityExt.getAssociationList(), workOrderFormEntityExt.getBusinessRules(),
                            workOrderFormEntityExt.getSummary(), workOrderFormEntityExt.getFieldPosition(), DistributorMarkEnum.OTHER.getCode());
                    paasFormEntityExt.setId(workOrderFormEntityExt.getId());
                } else {
                    paasFormEntityExt = paasFormModel.getByKey(formDataSaveDTO.getFormId(), formDataSaveDTO.getCorpid());
                }
                if (Objects.isNull(paasFormEntityExt)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                if (Objects.equals(paasFormEntityExt.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    // 经销商,前端没传distributorMark，传了dataId
                    formDataSaveDTO.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                    return distributorFormDataService.add(formDataSaveDTO);
                }
            }
            FormDataService formDataService = formDataServiceFactory.getFormDataService(businessType, saasMark);
            formDataSaveVO = formDataService.addAndImport(formDataSaveDTO);

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库保存表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataSaveVO;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public FormDataAddVO addByOnlyRepeatValidate(FormDataAddDTO formDataSaveDTO) throws XbbException {
        FormDataAddVO formDataSaveVO;
        Integer businessType = formDataSaveDTO.getBusinessType();
        Integer saasMark = formDataSaveDTO.getSaasMark();
        try {
            String corpid = formDataSaveDTO.getCorpid();
            if (!Objects.equals(formDataSaveDTO.getIsImport(), BasicConstant.ONE)) {
                XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
                //非导入时判断数据量限制
                Integer oneStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.ONE_FORM_DATA_NUM, 1, xbbRefTypeEnum, formDataSaveDTO.getFormId());
                Integer allStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, 1);
                if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
                }

                if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
                }
            }

            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataSaveDTO.getFormId(), formDataSaveDTO.getCorpid());

            if (Objects.isNull(paasFormEntityExt)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }

            AbstractFineClueService formDataService = fineClueServiceMap.get(businessType);
            // 改成不做必填校验

            BeforeSaveVO beforeSaveVO = formDataService.beforeSaveNoValidate(formDataSaveDTO);

            SaveVO saveVO = formDataService.save(formDataSaveDTO, beforeSaveVO, paasFormEntityExt, beforeSaveVO.getPaasFormDataEntity());
            formDataSaveVO = formDataService.afterSave(formDataSaveDTO, beforeSaveVO, saveVO, paasFormEntityExt, saveVO.getPaasFormDataEntity());
            formDataSaveVO.setFormDataId(saveVO.getDataId());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库保存表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataSaveVO;
    }


    /**
     * 开启严控后流水号生成
     * @param formDataSaveDTO
     * @param corpid
     * @param businessType
     * @param explainMap
     * @return
     * @throws XbbException
     */
    @Override
    public PaasFormDataEntity setSerialNo(FormDataAddDTO formDataSaveDTO, String corpid, Integer businessType, Map<String, FieldAttrEntity> explainMap) throws XbbException {
        return serialNoService.setSerialNo(formDataSaveDTO, corpid, businessType, explainMap);
    }

    /**
     * 判断是否去生成流水号
     * @param formDataSaveDTO
     * @param businessType
     * @param fieldAttrEntity
     * @return
     */
    public static boolean isToCreateSerialNo(FormDataAddDTO formDataSaveDTO, Integer businessType, FieldAttrEntity fieldAttrEntity) {
        return SerialNoUtil.isToCreateSerialNo(formDataSaveDTO.getGroupNumber(), formDataSaveDTO.getIsImport(), formDataSaveDTO.getSerialNo(), businessType, fieldAttrEntity);

    }

    /**
     * 开启严控模式后，生成相应的流水号
     * @param formDataSaveDTO
     * @param corpid
     * @param fieldAttrEntity
     * @throws XbbException
     */
    private void getSerialNo(FormDataAddDTO formDataSaveDTO, String corpid, FieldAttrEntity fieldAttrEntity) throws XbbException {
        if (Objects.nonNull(fieldAttrEntity)){
            if (Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ONE)){
                // 校验流水号是否重复
                Boolean flag = false;
                Boolean isQuotation = false;
                if (Objects.equals(formDataSaveDTO.getBusinessType(), XbbRefTypeEnum.QUOTATION.getCode())){
                    isQuotation = true;
                }
                while (!flag){
                    String serialNo = saasSaveHelp.getSerialNo(corpid, formDataSaveDTO.getFormId(), fieldAttrEntity);
                    if (isQuotation){
                        serialNo = serialNo+StringConstant.DEFAULT_VERSION;
                    }
                    formDataSaveDTO.setSerialNo(serialNo);
                    // 校验流水号是否重复
                    FormDataRepeatDTO formDataRepeatDTO = new FormDataRepeatDTO();
                    BeanUtil.copyProperties(formDataSaveDTO,formDataRepeatDTO);
                    formDataRepeatDTO.setSerialNo(serialNo);
                    formDataRepeatDTO.setValue(serialNo);
                    flag = repeat(formDataRepeatDTO).getNoRepeat();
                    if ( flag ) {
                        if ( Objects.nonNull(formDataSaveDTO.getFormId()) ) {
                            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataSaveDTO.getFormId(), corpid);
                            if ( Objects.isNull(paasFormEntityExt) ) {
                                return;
                            }
                            String userId = Objects.toString(formDataSaveDTO.getUserId(), "");
                            String userName = Objects.toString(formDataSaveDTO.getLoginUserName(), "");
                            // 记录日志
                            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_CREATE_SERIAL_NO), userName, paasFormEntityExt.getName(), serialNo);
                            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.SERIAL_NO, OperateTypeEnum.NEW, paasFormEntityExt.getId().toString(), paasFormEntityExt.getName(), memo, formDataSaveDTO.getHttpHeader());
                        }
                    }
                }
            }
        }
    }

    @Override
    public void batchAddContact(List<ValidateDataDTO> validateDataDTOS, Long customerId, String name, UserVO userVO ,String attr, XbbRefTypeEnum xbbRefTypeEnum) throws XbbException {

        if (Objects.nonNull(validateDataDTOS) && !validateDataDTOS.isEmpty() && !Objects.equals(validateDataDTOS.get(0).getIsImport(), BasicConstant.ONE)) {
            //非导入时判断数据量限制
            Integer oneStatus = packageStatusHelp.getPackageStatus(userVO.getCorpid(), ValueAddedTypeEnum.ONE_FORM_DATA_NUM, validateDataDTOS.size(), xbbRefTypeEnum,
                    validateDataDTOS.get(0).getFormId());
            Integer allStatus = packageStatusHelp.getPackageStatus(userVO.getCorpid(), ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, validateDataDTOS.size());
            if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
            }

            if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
            }
        }
        String labelAttr = null;
        Map<String, Long> labelPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.nonNull(validateDataDTOS) && !validateDataDTOS.isEmpty() && Objects.equals(validateDataDTOS.get(0).getIsImport(), BasicConstant.ONE)) {
            PaasFormExplainEntity contactExplain = paasFormExplainModel.getByBusinessType(xbbRefTypeEnum.getCode(), validateDataDTOS.get(0).getCorpid());
            List<FieldAttrEntity> explainList = JSONArray.parseArray(contactExplain.getExplains(), FieldAttrEntity.class);
            for (FieldAttrEntity item : explainList) {
                if (Objects.equals(item.getFieldType(), FieldTypeEnum.LABEL.getType())) {
                    labelAttr = item.getAttr();
                }
            }

            if (StringUtil.isNotEmpty(labelAttr)) {
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("formId", contactExplain.getFormId());
                param.put("corpid", contactExplain.getCorpid());
                param.put("appId", contactExplain.getAppId());
                param.put("del", DelEnum.NORMAL.getDel());
                List<LabelEntity> entitys = labelModel.findEntitys(param);
                entitys.forEach(item -> {
                    labelPojoMap.put(item.getName(), item.getId());
                });
            }
        }


        for ( ValidateDataDTO validateDataDTO : validateDataDTOS ) {
            if (Objects.isNull(validateDataDTO.getSerialNo())){
                validateDataDTO.setSerialNo("");
            }
            JSONObject data = validateDataDTO.getData();
            if ( data.isEmpty() ) {
                continue;
            }

            if (StringUtil.isNotEmpty(labelAttr)){
                JSONArray jsonArray = new JSONArray();
                if (data.get(labelAttr) instanceof  String){
                    if (Objects.nonNull(data.get(labelAttr))){
                        String[] split = data.getString(labelAttr).split(",");
                        for (String s : split) {
                            if (Objects.nonNull(labelPojoMap.get(s))) {
                                jsonArray.add(labelPojoMap.get(s));
                            }
                        }
                    }
                    data.put(labelAttr, jsonArray);
                }
            }

            if (Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), xbbRefTypeEnum.getCode())) {
                data.put(ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr(), name);
            } else if (Objects.equals(XbbRefTypeEnum.SUPPLIER_CONTACT.getCode(), xbbRefTypeEnum.getCode())) {
                data.put(SupplierContactEnum.SUPPLIER_ID_LINK_TEXT.getAttr(), name);
            }

            // 把关联客户id塞进去
            data.put(attr, customerId);
            saasSaveHelp.dealLabelData(validateDataDTO.getData(), validateDataDTO.getExplainMap());
            FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
            BeanUtil.copyProperties(validateDataDTO, formDataAddDTO);
            formDataAddDTO.setLoginUser(userVO);
            formDataAddDTO.setDataList(data);
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(formDataAddDTO, paasFormDataEntity);
            String ownerId = formDataAddDTO.getUserId();
            if ( Objects.nonNull(validateDataDTO.getOwnerIds()) && !validateDataDTO.getOwnerIds().isEmpty() ) {
                paasFormDataEntity.setOwnerId(validateDataDTO.getOwnerIds().get(0).getId().toString());
            }else {
                paasFormDataEntity.setOwnerId(ownerId);
            }
            paasFormDataEntity.setData(formDataAddDTO.getDataList());
            // 所属部门的id，由前端传入
            paasFormDataEntity.setDepartmentId(formDataAddDTO.getDepartmentId());
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataAddDTO.getFormId(), formDataAddDTO.getCorpid());
            if ( paasFormEntityExt == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            paasFormDataEntity.setMenuId(paasFormEntityExt.getMenuId());
            paasFormDataEntity.setFlowStatus(FlowStatusEnum.NOT_NEED_APPROVAL.getType());
            if ( validateDataDTO.getProcessCreatorId() == null ) {
                paasFormDataEntity.setCreatorId(formDataAddDTO.getUserId());
            } else {
                paasFormDataEntity.setCreatorId(validateDataDTO.getProcessCreatorId());
            }
            PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(validateDataDTO.getFormId(), validateDataDTO.getCorpid());
            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), null);
            // 流水号开启严控模式
            FieldAttrEntity fieldAttrEntity = explainMap.get(FieldTypeEnum.SERIALNO.getAlias());
            if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getStrictController(), BasicConstant.ONE)) {
                FormDataAddDTO formDataSaveDTO = new FormDataAddDTO();
                BeanUtil.copyProperties(validateDataDTO, formDataSaveDTO);
                formDataSaveDTO.setFormId(formDataAddDTO.getFormId());
                getSerialNo(formDataSaveDTO, validateDataDTO.getCorpid(), fieldAttrEntity);
                paasFormDataEntity.setSerialNo(formDataSaveDTO.getSerialNo());
                formDataAddDTO.getDataList().put(FieldTypeEnum.SERIALNO.getAlias(),formDataSaveDTO.getSerialNo());
                formDataAddDTO.setSerialNo(formDataSaveDTO.getSerialNo());
            }
            // 是否往form_data表中插入数据
            Integer noApprovalRequired = 1;
            if(Objects.equals(paasFormEntityExt.getIsProcessForm(), 1) && !Objects.equals(validateDataDTO.getIsImport(),1)){
                StartProcessDTO startProcessDTO = new StartProcessDTO();
                BeanUtil.copyProperties(formDataAddDTO, startProcessDTO);
                startProcessDTO.setFormId(paasFormEntityExt.getId());
                startProcessDTO.setData(formDataAddDTO.getDataList());
                startProcessDTO.setFormDataId(0L);
                startProcessDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                startProcessDTO.setBusinessType(xbbRefTypeEnum.getCode());
                startProcessDTO.setCreatorId(paasFormDataEntity.getCreatorId());
                StartProcessVO startProcessVO = processStartHelp.startProcess(startProcessDTO, null);
                if (Objects.isNull(startProcessVO)) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
                }
                noApprovalRequired = startProcessVO.getNoApprovalRequired();
            }
            if ( noApprovalRequired.equals(1) ) {
                //保存区分
                proModelService.insert(formDataAddDTO, paasFormDataEntity, paasFormEntityExt);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public FormDataUpdateVO update(FormDataUpdateDTO formDataUpdateDTO) throws XbbException {
        FormDataUpdateVO formDataSaveVO = new FormDataUpdateVO();
        Integer businessType = formDataUpdateDTO.getBusinessType();
        Integer saasMark = formDataUpdateDTO.getSaasMark();
        try {
            FormDataUpdateService abstractFormDataUpdateService = formDataUpdateServiceFactory.getFormDataUpdateService(businessType, saasMark);
            if (Objects.nonNull(abstractFormDataUpdateService) && !Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), formDataUpdateDTO.getDistributorMark())) {
                if (Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode())) {
                    // 校验工作报告类型
                    JSONObject typeObject = formDataUpdateDTO.getDataList().getJSONObject(WorkReportFieldEnum.TYPE.getAttr());
                    Integer type = typeObject.getInteger("value");
                    WorkReportTypeEnum workReportTypeEnum = WorkReportTypeEnum.getByType(type);
                    if(Objects.isNull(workReportTypeEnum)){
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100028 ,MessageConstant.ABNORMAL_PARAMETER, WorkReportDailyEnum.TYPE.getAttrName());
                    }
                    if (!Objects.equals(formDataUpdateDTO.getSubBusinessType(), workReportTypeEnum.getBusinessType())){
                        formDataUpdateDTO.setSubBusinessType(workReportTypeEnum.getBusinessType());
                    }
                    PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(formDataUpdateDTO.getSubBusinessType(), formDataUpdateDTO.getCorpid());
                    // 重新设置formId，获取正确解释
                    Long workReportFormId = Objects.nonNull(paasFormEntityExt) ? paasFormEntityExt.getId() : formDataUpdateDTO.getFormId();
                    formDataUpdateDTO.setFormId(workReportFormId);
                }
                return abstractFormDataUpdateService.updateAndImport(formDataUpdateDTO);
            }
            BeforeUpdateVO beforeUpdateVO = abstractFormDataUpdateService.beforeSave(formDataUpdateDTO);
            //是否触发工作流
            if (formDataUpdateDTO.getIsSatisfyTrigger()) {
                String pojo = JSON.toJSONString(beforeUpdateVO.getSaasNeedRedundantAttrPojo(), SerializerFeature.DisableCircularReferenceDetect);
                SaasNeedRedundantAttrPojo needRedundantAttrPojo = JSON.parseObject(pojo, SaasNeedRedundantAttrPojo.class);
                Integer flowStatus;
                if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                    flowStatus = beforeUpdateVO.getWorkOrderEntity().getFlowStatus();
                    beforeUpdateVO.getWorkOrderEntity().setFlowStatus(null);
                } else {
                    flowStatus = beforeUpdateVO.getPaasFormDataEntity().getFlowStatus();
                    beforeUpdateVO.getPaasFormDataEntity().setFlowStatus(null);
                }
                // 此处不更新flowStatus，避免用户无改动数据时，审批通过的数据flowStatus从2改成1，导致触发工作流
                UpdateVO updateVO = abstractFormDataUpdateService.updateForWorkflow(formDataUpdateDTO, beforeUpdateVO, beforeUpdateVO.getPaasFormEntityExt(), beforeUpdateVO.getPaasFormDataEntity(), beforeUpdateVO.getOldPaasFormData());
                // 是否真的编辑，true是
                boolean isEdit = Objects.equals(updateVO.getUpdateLine(), 1);

                //如果团队有需审批字段，数据有改动，也触发工作流
                isEdit = isEdit || formDataUpdateDTO.getTeamIsEdit();

                if (isEdit) {
                    // 真的编辑了走工作流
                    formDataSaveVO = abstractFormDataUpdateService.afterSaveForWorkflow(formDataUpdateDTO, beforeUpdateVO, updateVO, beforeUpdateVO.getPaasFormEntityExt(), beforeUpdateVO.getPaasFormDataEntity(), beforeUpdateVO.getOldPaasFormData());
                    formDataSaveVO.setFormDataId(updateVO.getDataId());
                    formDataSaveVO.setBackupDataId(beforeUpdateVO.getBackupDataId());
                    beforeUpdateVO.setSaasNeedRedundantAttrPojo(needRedundantAttrPojo);
                    // 为了保证用户在有修改数据的时候才触发工作流，将flowStatus进行分开更新
                    PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                    paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
                    paasProcessDataEntity.setFormDataId(formDataUpdateDTO.getDataId());
                    paasProcessDataEntity.setBusinessType(businessType);
                    paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
                    proModelService.updateFormDataStatus(paasProcessDataEntity, flowStatus);
                    workflowFormDataOperationService.workflowUpdateTrigger(formDataUpdateDTO, beforeUpdateVO, formDataSaveVO);
                } else {
                    // 不走工作流
                    // 补充在updateForWorkflow中剔除的文件柜逻辑
                    if (Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
                        abstractFormDataUpdateService.saveFile(beforeUpdateVO.getExplainMap(), updateVO.getWorkOrderEntity(), formDataUpdateDTO.getBusinessType(), updateVO.getUserVO());
                    } else {
                        abstractFormDataUpdateService.saveFile(beforeUpdateVO.getExplainMap(), updateVO.getPaasFormDataEntity(), formDataUpdateDTO.getBusinessType(), updateVO.getUserVO());
                    }
                    formDataSaveVO = abstractFormDataUpdateService.afterSave(formDataUpdateDTO, beforeUpdateVO, updateVO, beforeUpdateVO.getPaasFormEntityExt(), beforeUpdateVO.getPaasFormDataEntity(), beforeUpdateVO.getOldPaasFormData());
                    formDataSaveVO.setFormDataId(updateVO.getDataId());
                }
            } else {
                UpdateVO updateVO = abstractFormDataUpdateService.update(formDataUpdateDTO, beforeUpdateVO, beforeUpdateVO.getPaasFormEntityExt(), beforeUpdateVO.getPaasFormDataEntity(), beforeUpdateVO.getOldPaasFormData());
                // 经销商特殊处理
                Integer noApprovalRequired = beforeUpdateVO.getNoApprovalRequired();
                if (DistributorMarkEnum.DISTRIBUTOR.getCode().equals(formDataUpdateDTO.getDistributorMark())) {
                    if (Objects.equals(beforeUpdateVO.getNoApprovalRequired(), 1) ) {
                        PaasFormEntityExt paasFormEntityExt = beforeUpdateVO.getPaasFormEntityExt();
                        PaasFormDataEntity paasFormDataEntity = updateVO.getPaasFormDataEntity();
                        PaasFormDataEntity oldPaasFormDataEntity = beforeUpdateVO.getOldPaasFormData();
                        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(oldPaasFormDataEntity.getFormId(), oldPaasFormDataEntity.getCorpid());
                        List<FieldAttrEntity> fieldList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                        AfterSaveVO afterSaveVO = distributorProModelService.update(formDataUpdateDTO, updateVO.getPaasFormDataEntity(), beforeUpdateVO.getOldPaasFormData(), beforeUpdateVO.getPaasFormEntityExt());
                        if ( Objects.equals(afterSaveVO.getCode(), PaasConstant.FORM_ADD_PROCESS_RETURN_CODE) ) {
                            formDataSaveVO.setMsg(afterSaveVO.getMsg());
                            formDataSaveVO.setCode(afterSaveVO.getCode());
                        } else {
                            formDataSaveVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_RETURN_MSG));
                            formDataSaveVO.setCode(PaasConstant.FORM_ADD_RETURN_CODE);
                            String businessRules = paasFormEntityExt.getBusinessRules();
                            if (!commonHelp.isOpenWorkFlow(formDataUpdateDTO.getCorpid()) && Objects.equals("1", businessRules) && Objects.equals(1, afterSaveVO.getSuccess())) {
                                paasFormDataEntity.setCreatorId(oldPaasFormDataEntity.getCreatorId());
                                paasFormDataEntity.setAddTime(oldPaasFormDataEntity.getAddTime());
                                paasFormDataEntity.setUpdateTime(oldPaasFormDataEntity.getUpdateTime());
                                PaasFormDataEntity newFormData = proModelService.getOldPaasFormDataEntity(formDataUpdateDTO);
                                IndexTypeEnum indexTypeEnum = indexTypeModel.getSubIndexType(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getSaasMark());
                                paasFormSubDataModel.transferSubForm(newFormData, indexTypeEnum);
                                paasFormSubDataModel.transferSubForm(oldPaasFormDataEntity, indexTypeEnum);
                                ActiveRuleDTO activeRuleDTO = new ActiveRuleDTO(new ArrayList<>(), newFormData,  oldPaasFormDataEntity, fieldList, formDataUpdateDTO.getDataId(),
                                        formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getSaasMark(), formDataUpdateDTO.getCorpid(),formDataUpdateDTO.getLoginUser(), 1, formDataUpdateDTO.getPlatform(),
                                        formDataUpdateDTO.getHttpHeader(), formDataUpdateDTO.getBrowserInfo(), formDataUpdateDTO.getIp(), formDataUpdateDTO.getLocale(), formDataUpdateDTO.getIsImport());
                                formDataActiveRuleHelp.activeRule(activeRuleDTO);
                            }
                        }
                    }else if (Objects.equals(noApprovalRequired, 2)) {
                        // 自动拒绝
                        formDataSaveVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                        formDataSaveVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
                    } else {
                        formDataSaveVO.setMsg(I18nMessageUtil.getMessage(MessageConstant.FORM_ADD_PROCESS_RETURN_MSG));
                        formDataSaveVO.setCode(PaasConstant.FORM_ADD_PROCESS_RETURN_CODE);
                        PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                        paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
                        paasProcessDataEntity.setFormDataId(formDataUpdateDTO.getDataId());
                        paasProcessDataEntity.setBusinessType(businessType);
                        paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
                        proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
                    }

                } else {
                    formDataSaveVO = abstractFormDataUpdateService.afterSave(formDataUpdateDTO, beforeUpdateVO, updateVO, beforeUpdateVO.getPaasFormEntityExt(), beforeUpdateVO.getPaasFormDataEntity(), beforeUpdateVO.getOldPaasFormData());
                }
                formDataSaveVO.setFormDataId(updateVO.getDataId());
            }
            return formDataSaveVO;
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库保存表单数据出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }



    @Deprecated
    @Override
    public void batchEditContact(String corpid, List<ValidateDataDTO> needAddValidateDataDTO, List<ValidateDataDTO> needUpdateValidateDataDTO, List<ValidateDataDTO> needDelValidateDataDTO, Long customerId, String name, UserVO userVO, String attr, XbbRefTypeEnum xbbRefTypeEnum, String processCreatorId, Integer isFromProcess) throws XbbException {
        if ( needUpdateValidateDataDTO != null ) {
            for ( ValidateDataDTO validateDataDTO : needUpdateValidateDataDTO ) {
                JSONObject data = validateDataDTO.getData();
                if ( data.isEmpty() ) {
                    continue;
                }
                FormDataUpdateDTO formDataUpdateDTO = new FormDataUpdateDTO();
                BeanUtil.copyProperties(validateDataDTO, formDataUpdateDTO);
                formDataUpdateDTO.setDataList(data);
                PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
                BeanUtil.copyProperties(formDataUpdateDTO, paasFormDataEntity);
                paasFormDataEntity.setId(formDataUpdateDTO.getDataId());
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataUpdateDTO.getFormId(), formDataUpdateDTO.getCorpid());
                if ( paasFormEntityExt == null ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                if ( formDataUpdateDTO.getDataList() != null ) {
                    paasFormDataEntity.setData(formDataUpdateDTO.getDataList());
                }
                paasFormDataEntity.setMenuId(paasFormEntityExt.getMenuId());
                paasFormDataEntity.setCreatorId(validateDataDTO.getCreatorId());
                if ( Objects.nonNull(formDataUpdateDTO.getOwnerId()) && !formDataUpdateDTO.getOwnerId().isEmpty() ) {
                    paasFormDataEntity.setOwnerId(Objects.toString(formDataUpdateDTO.getOwnerId().get(0).getId(), ""));
                }
                PaasFormDataEntity oldPaasFormDataEntity = proModelService.getOldPaasFormDataEntity(formDataUpdateDTO);
                Integer noApprovalRequired = 1;
                if ( paasFormEntityExt.getIsProcessForm().equals(1) && !Objects.equals(formDataUpdateDTO.getIsImport(), 1) ) {
                    StartProcessDTO startProcessDTO = new StartProcessDTO();
                    BeanUtil.copyProperties(formDataUpdateDTO, startProcessDTO);
                    startProcessDTO.setOwnerId(paasFormDataEntity.getOwnerId());
                    startProcessDTO.setData(formDataUpdateDTO.getDataList());
                    startProcessDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                    startProcessDTO.setFormDataId(formDataUpdateDTO.getDataId());
                    //审批中用审批创建人，无审批用当前登录人
                    if (Objects.equals(isFromProcess, BasicConstant.ONE)) {
                        startProcessDTO.setCreatorId(processCreatorId);
                    }else {
                        startProcessDTO.setCreatorId(formDataUpdateDTO.getUserId());
                    }
                    //LOG.info("到联系人审批中的userId:{}", formDataUpdateDTO.getUserId());
                    startProcessDTO.setBusinessType(xbbRefTypeEnum.getCode());
                    StartProcessVO startProcessVO = processStartHelp.startProcess(startProcessDTO, oldPaasFormDataEntity);
                    if ( Objects.isNull(startProcessVO) ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.START_PROCESS_ERROR);
                    }
                    noApprovalRequired = startProcessVO.getNoApprovalRequired();
                }
                if(noApprovalRequired.equals(1)){
                    proModelService.update(formDataUpdateDTO, paasFormDataEntity, oldPaasFormDataEntity, paasFormEntityExt);
                    SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = validateDataDTO.getSaasNeedRedundantAttrPoJo();
                    if (Objects.nonNull(saasNeedRedundantAttrPoJo)) {
                        teamDataHelp.saveUserTeam(saasNeedRedundantAttrPoJo, paasFormDataEntity.getId(),paasFormDataEntity,formDataUpdateDTO.getIsImport(), false);
                    }
                }else {
                    PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                    paasProcessDataEntity.setCorpid(formDataUpdateDTO.getCorpid());
                    paasProcessDataEntity.setFormDataId(oldPaasFormDataEntity.getId());
                    paasProcessDataEntity.setBusinessType(xbbRefTypeEnum.getCode());
                    paasProcessDataEntity.setSaasMark(formDataUpdateDTO.getSaasMark());
                    proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
                }
            }
        }
        List<Long> delDataId = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if ( needDelValidateDataDTO != null ) {
            for ( ValidateDataDTO needDelDTO : needDelValidateDataDTO ) {
                Long dataId = needDelDTO.getDataId();
                if ( dataId != null ) {
                    delDataId.add(dataId);
                }
            }
        }
        if ( CollectionsUtil.isNotEmpty(delDataId) ) {
            switch (xbbRefTypeEnum) {
                case CONTACT:
                    contactModel.deleteBatch(delDataId, corpid);
                    //同时也要删除联系人团队信息
                    contactUserModel.deleteBatchByContactIdIn(delDataId, corpid);
                    break;
                case SUPPLIER_CONTACT:
                    supplierContactModel.deleteBatch(delDataId, corpid);
                    break;
            }
        }
        if ( needAddValidateDataDTO != null ) {
            ////审批中用审批创建人，无审批用当前登录人
            if (Objects.equals(isFromProcess, BasicConstant.ONE)) {
                needAddValidateDataDTO.forEach(validateDataDTO -> validateDataDTO.setProcessCreatorId(processCreatorId));
            }else {
                needAddValidateDataDTO.forEach(validateDataDTO -> validateDataDTO.setProcessCreatorId(validateDataDTO.getUserId()));
            }
            batchAddContact(needAddValidateDataDTO, customerId, name, userVO, attr, xbbRefTypeEnum);
        }
    }

    @Override
    public FormDataOwnerVO updateOwner(FormDataOwnerDTO formDataOwnerDTO) throws XbbException {
        FormDataOwnerVO formDataOwnerVO = new FormDataOwnerVO();
        try {
            PaasFormDataEntity entity = paasFormDataModel.getByKey(formDataOwnerDTO.getFormDataId(), formDataOwnerDTO.getCorpid());
            if ( entity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            BeanUtil.copyProperties(formDataOwnerDTO, paasFormDataEntity);
            paasFormDataModel.update(paasFormDataEntity);
            // 记录日志
            String corpid = formDataOwnerDTO.getCorpid();
            String userId = formDataOwnerDTO.getUserId();

            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA_OWNER), formDataOwnerDTO.getLoginUserName(), paasFormDataEntity.getFormId(), entity.getOwnerId(), paasFormDataEntity.getOwnerId());
            mongoLogHelp.buildLog(corpid, userId, formDataOwnerDTO.getLoginUserName(), OperateModuleTypeEnum.PAAS_FORM_DATA, OperateTypeEnum.EDIT, formDataOwnerDTO.getAppId().toString(), "", memo, formDataOwnerDTO.getHttpHeader());

            formDataOwnerVO.setAppId(formDataOwnerDTO.getAppId());
            formDataOwnerVO.setFormDataId(formDataOwnerDTO.getFormDataId());
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库更新负责人/拥有者出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataOwnerVO;
    }

    @Override
    public FormDataAddGetVO addGet(FormDataAddGetDTO formDataAddGetDTO) throws XbbException {
        FormDataAddGetVO formDataAddGetVO = new FormDataAddGetVO();
        BusinessNewPageRenderService businessNewPageRenderService = businessNewPageRenderMap.get(formDataAddGetDTO.getBusinessType());
        if (Objects.nonNull(businessNewPageRenderService) && !Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), formDataAddGetDTO.getDistributorMark())) {
            return businessNewPageRenderService.addGet(formDataAddGetDTO);
        }
        VerifyAddPermissionDTO verifyAddPermissionDTO = new VerifyAddPermissionDTO();
        BeanUtil.copyProperties(formDataAddGetDTO, verifyAddPermissionDTO);
        ProPermissionHelp.verifyAddPermission(verifyAddPermissionDTO);
        try {
            // 低代码
            Long formId = formDataAddGetDTO.getFormId();
            Integer businessType = formDataAddGetDTO.getBusinessType();
            String corpid = formDataAddGetDTO.getCorpid();

            if ( Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType) ) {
                //工单
                formDataAddGetVO = workOrderFormDataService.addGet(formDataAddGetDTO);
                return formDataAddGetVO;
            }else if (Objects.equals(XbbRefTypeEnum.PAYMENT.getCode(), businessType)
                    && !Objects.equals(XbbRefTypeEnum.RED_RECEIVABLES.getCode(), formDataAddGetDTO.getDifferenceBusinessType())) {
                Long nowModelType = fundSetService.getModelType(formDataAddGetDTO.getCorpid(),XbbRefTypeEnum.CRM);
                if (!Objects.equals(nowModelType, ModelTypeEnum.PLAN.getCode())) {
                    throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208079);
                }
            }
            LowCodeConfigGetDTO lowCodeConfigGetDTO = new LowCodeConfigGetDTO();
            lowCodeConfigGetDTO.setCorpid(corpid);
            lowCodeConfigGetDTO.setFormId(formId);
            lowCodeConfigGetDTO.setBusinessType(businessType);
            lowCodeConfigGetDTO.setLoginUser(formDataAddGetDTO.getLoginUser());
            lowCodeConfigGetDTO.setType(ButtonTypeEnum.ADD.getCode());
            LowCodeConfigGetVO lowCodeConfig = lowCodeConfigService.get(lowCodeConfigGetDTO);
            formDataAddGetVO.setLowCodeConfig(lowCodeConfig);
            //确认是否为创建回/付款单
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
            boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
            // 经销商标识
            Integer distributorMark = formDataAddGetDTO.getDistributorMark();
            PaasFormEntityExt paasFormEntityExt;
            if (sheetFlag) {
                //如果是回款，则都是公用回款单模板（预收款的formId是预收款余额的隐藏form，而非回款单的formId，因此要用businessType读取）
                paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(sheetTypeEnum.getXbbRefTypeEnum().getCode(), corpid, distributorMark, null);
                //置为回款单的formId
                formId = paasFormEntityExt.getId();
            }else if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT.getCode())
                    && !Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                //因为现在应收款快捷新建那边新建默认的是pro这边的应收款新建，但是快捷新建那边的formId是随机的，有可能传的是经销商的formId。所以这边需要重新去查询一下
                paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PAYMENT.getCode(), corpid,
                        DistributorMarkEnum.OTHER.getCode(), null);
                //置为普通应收款的formId
                formId = paasFormEntityExt.getId();
            } else {
                paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
            }
            if ( Objects.isNull(paasFormEntityExt) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018, MessageConstant.FORM_NOT_EXIST);
            }
            if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode()) || Objects.equals(paasFormEntityExt.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                formDataAddGetDTO.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
                formDataAddGetVO = distributorFormDataService.addGet(formDataAddGetDTO);
                formDataAddGetVO.setLowCodeConfig(lowCodeConfig);
                return formDataAddGetVO;
            }
            saasAddHelp.handleFormEntity(paasFormEntityExt, formDataAddGetDTO.getSaasMark(), formDataAddGetDTO.getBusinessType());
            formDataAddGetVO.setPaasFormEntity(paasFormEntityExt);
            if ( formDataAddGetDTO.getFormId() == null ) {
                formDataAddGetDTO.setFormId(paasFormEntityExt.getId());
            }
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
            if ( Objects.isNull(paasFormExplainEntity) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            // fix: 20682 【成功部】移动端周报统计数据没出来，电脑上正常
            if ( Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), businessType) ) {
                formDataAddGetDTO.setSubBusinessType(paasFormEntityExt.getBusinessType());
            }

            // 查看是否能使用精线索的工商查询
            if (fineClueHelp.isBusinessSearch(corpid, businessType, distributorMark)) {
                formDataAddGetVO.setIsFineClue(1);
            }
            // 获取字段解释信息，并且过滤不可见字段 start
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            //根据套餐判断负责人属性
            Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
            boolean ultimateTag = Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
            if(!ultimateTag && FormOwnerUniqueEnum.getDefaultBusinessList().contains(businessType)){
                //只有旗舰版支持负责人唯一设置，其他版本拿默认设置
                FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                Integer multiple = formOwnerUniqueEnum.getValue();
                for (FieldAttrEntity fieldAttrEntity : explainList) {
                    if(Objects.equals(fieldAttrEntity.getAttr(),FieldTypeEnum.OWNERID.getAlias())){
                        fieldAttrEntity.setMultiple(multiple);
                    }
                }
            }
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataAddGetDTO, handlerExplainDTO, false);
            handlerExplainDTO.setExplainList(explainList);
            handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);
            HandlerExplainVO handlerExplainVO = formDataAddFormExplainHandlerName.handleExplain(handlerExplainDTO);
            if ( handlerExplainVO == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            explainList = handlerExplainVO.getHeadList();
            if (sheetFlag) {
                //如果是回/付款单、其他收入/支出单，则根据数据data内的回/付款单/其他收入/支出单类型重置sheetTypeEnum（前端传过来的businessType可能没有详细区分哪种类型回/付款单/其他收入/支出单）
                fundHelp.handlePaymentSheet(true, sheetTypeEnum, explainList, corpid, distributorMark);
                fundHelp.setBySheetType(paasFormEntityExt, sheetTypeEnum);
            }
            // 查询客户名称和电话判重设置
            if ( Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                handlerCustomerRepeat(corpid, formId, explainList, businessType);
            }
            String serialNo = "";
            Boolean strictSeri= true;
            List<String> unableEditMemo= Arrays.asList(I18nMessageUtil.getMessage(StringConstant.AUTO_GEN_FIELD, Locale.US), I18nMessageUtil.getMessage(StringConstant.AUTO_GEN_FIELD, Locale.CHINA));
            for ( FieldAttrEntity fieldAttrEntity : explainList ) {
                // 获取流水号
                if (fieldAttrEntity.getFieldType() != null && fieldAttrEntity.getFieldType().equals(FieldTypeEnum.SERIALNO.getType())) {
//                    if ( Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
//                        if ( Objects.equals(fieldAttrEntity.getStrictController(), Constant.ZERO) ) {
//                            serialNo = saasSaveHelp.getSerialNo(serialNo, corpid, formId, fieldAttrEntity);
//                            strictSeri = false;
//                        }
//                    } else if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_ORDER.getCode())) {
//                        if(Objects.equals(fieldAttrEntity.getStrictController(), Constant.ZERO)){
//                            serialNo = saasSaveHelp.getSerialNo(serialNo, corpid, formId, fieldAttrEntity);
//                            strictSeri = false;
//                        }
//                    } else {
//                        if ( Objects.equals(fieldAttrEntity.getStrictController(), Constant.ZERO) ) {
//                            serialNo = saasSaveHelp.getSerialNo(serialNo, corpid, formId, fieldAttrEntity);
//                            strictSeri = false;
//                        }
//                    }
                    if ( Objects.equals(fieldAttrEntity.getStrictController(), Constant.ZERO) ) {
                        serialNo = saasSaveHelp.getSerialNo(serialNo, corpid, formId, fieldAttrEntity);
                        strictSeri = false;
                    }
                }
                // fix:18442 【移动端、web端】新建、编辑页面，不展示系统自动生成字段
                if (unableEditMemo.contains(fieldAttrEntity.getUnableEditMemo())){
                    fieldAttrEntity.setVisible(0);
                }
                if ( Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
                    if (Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.PRODUCT.getAttr()) && FieldTypeEnum.SELECT_PRODUCT.getType().equals(fieldAttrEntity.getFieldType())) {
                        // 合同产品关联字段
                        List<? extends FieldAttrEntity> fieldAttrEntities = fieldAttrEntity.getSubForm().getItems();
                        for (int i = 0; i < fieldAttrEntities.size(); i++) {
                            FieldAttrEntity contractProductAttrEntity = fieldAttrEntities.get(i);
                            if (!SelectProductEnum.PRODUCT.getAttr().equals(contractProductAttrEntity.getAttr())) {
                                continue;
                            }
                            LinkInfoPojo linkInfo = contractProductAttrEntity.getLinkInfo();
                            if (Objects.nonNull(linkInfo) && Objects.nonNull(linkInfo.getLinkedAttr())) {
                                List<LinkedAttrPoJo> linkedAttrList = linkInfo.getLinkedAttr();
                                Iterator<LinkedAttrPoJo> iterator = linkedAttrList.iterator();
                                // 获取产品解释
                                PaasFormExplainEntity productExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
                                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(productExplainEntity.getExplains());
                                while (iterator.hasNext()) {
                                    LinkedAttrPoJo linkedAttrPoJo = iterator.next();
                                    FieldAttrEntity attrEntity = new FieldAttrEntity();
                                    if (SelectProductEnum.STOCK.getAttr().equals(linkedAttrPoJo.getAttr())) {
                                        attrEntity = explainMap.get(ProductEnum.STOCK.getAttr());
                                    } else if (SelectProductEnum.PRICE.getAttr().equals(linkedAttrPoJo.getAttr())) {
                                        attrEntity = explainMap.get(ProductEnum.PRICE.getAttr());
                                    } else if (SelectProductEnum.UNIT.getAttr().equals(linkedAttrPoJo.getAttr())) {
                                        attrEntity = explainMap.get(ProductEnum.UNIT.getAttr());
                                    }
                                    if (BasicConstant.ZERO.equals(attrEntity.getIsOpen())) {
                                        iterator.remove();
                                        if (Objects.nonNull(fieldAttrEntity.getSubForm().getItems())){
                                            FieldAttrEntity jsonObject = fieldAttrEntity.getSubForm().getItems().get(i);
                                            if (Objects.nonNull(jsonObject) && Objects.nonNull(jsonObject.getLinkInfo())) {
                                                jsonObject.getLinkInfo().setLinkedAttr(linkedAttrList);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (FieldTypeEnum.SELECT_PRODUCT.getType().equals(fieldAttrEntity.getFieldType())) {
                    DefaultAttrPoJo defaultAttr = fieldAttrEntity.getDefaultAttr();
                    if (Objects.nonNull(defaultAttr)) {
                        String defaultType = defaultAttr.getDefaultType();
                        if (DefaultTypeEnum.PRODUCT_DATA_RELY.getAlias().equals(defaultType)) {
                            List<RelyPoJo> relyPoJoList = paasFormExplainService.selectProductRely(formDataAddGetDTO.getCorpid(), formDataAddGetDTO.getFormId());
                            fieldAttrEntity.setRelyList(relyPoJoList);
                        }
                    }
                }
            }
            if ( Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) && StringUtil.isNotEmpty(serialNo)) {
                // 报价单编号是组号加版本号
                formDataAddGetVO.setGroupNumber(serialNo);
                serialNo = serialNo + StringConstant.DEFAULT_VERSION;
            }
            formDataAddGetVO.setSerialNo(serialNo);
            proDetailHandlerHelp.handelSaasSpecialItem(explainList, businessType, formDataAddGetDTO.getSubBusinessType(),
                    formDataAddGetDTO.getDifferenceBusinessType(), distributorMark);
            // 设置默认的关联数据
            paasFormHelp.setDefaultLinkData(explainList, formDataAddGetDTO, handlerExplainVO);
            // 获取字段解释信息，并且过滤不可见字段 end
            // 新建表单时SaaS某些字段赋初始值
            if ( Objects.equals(formDataAddGetDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode()) ) {
                if (RedundantTemplateTypeEnum.isMultiTemplate(businessType)) {
                    // 合同，客户模板选择
                    TemplateDTO templateDTO = new TemplateDTO();
                    BeanUtil.copyProperties(formDataAddGetDTO, templateDTO);
                    templateDTO.setSubBusinessType(templateDTO.getBusinessType());
                    List<EnablePojo> saasTemplateList = templateService.getSaasTemplateList(templateDTO);

                    FieldAttrEntity templateFieldAttrEntity = new FieldAttrEntity();
                    if (saasTemplateList.size() == 1) {
                        templateFieldAttrEntity.setVisible(0);
                    } else {
                        templateFieldAttrEntity.setVisible(1);
                    }
                    if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                        templateFieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.CONTRACT_TEMPLATE));
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
                        templateFieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.OPPORTUNITY_TEMPLATE));
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                        templateFieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.CLUE_TEMPLATE));
                    }else {
                        templateFieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.CUSTOMER_TEMPLATE));
                    }
                    templateFieldAttrEntity.setAttr(FieldTypeEnum.TEMPLATE.getAlias());
                    templateFieldAttrEntity.setAttrType(FieldTypeEnum.TEMPLATE.getEsalias());
                    templateFieldAttrEntity.setFieldType(FieldTypeEnum.TEMPLATE.getType());
                    templateFieldAttrEntity.setEditable(1);
                    templateFieldAttrEntity.setComboType(0);
                    templateFieldAttrEntity.setDefaultAttr(new DefaultAttrPoJo());
                    //新建一个集合用于存放ItemPoJo实体
                    List<ItemPoJo> templateItem = new ArrayList<>();

                    for (EnablePojo enablePojo : saasTemplateList) {
                        //创建ItemPoJo对象，并在value和text属性中设置数据
                        ItemPoJo itemPoJo = new ItemPoJo();
                        itemPoJo.setValue(enablePojo.getFormId());
                        itemPoJo.setText(enablePojo.getFormName());
                        if (Objects.equals(enablePojo.getFormId(), formId)) {
                            itemPoJo.setChecked(true);
                        }
                        //将最后满足的itemPoJo添加到templateItem集合中
                        templateItem.add(itemPoJo);
                    }
                    templateFieldAttrEntity.setItems(templateItem);
                    explainList.add(0, templateFieldAttrEntity);
                }

                if (formDataAddGetDTO.getSaasSpecialParamPojo() != null) {
                    // 各个业务场景，只有一个号码新建，直接break
                    String phoneNum = formDataAddGetDTO.getSaasSpecialParamPojo().getPhoneNum();
                    for (FieldAttrEntity item : explainList) {
                        if (Objects.equals(item.getAttr(), CustomerManagementEnum.PHONE.getAttr())) {
                            if (phoneNum != null) {
                                JSONArray phoneArray = new JSONArray();
                                JSONObject phoneObject = new JSONObject();
                                phoneObject.put(StringConstant.PHONE_TYPE_ATTR, "1");
                                phoneObject.put(StringConstant.PHONE_TEL_ATTR, phoneNum);
                                phoneArray.add(phoneObject);
                                item.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(phoneArray));
                                break;
                            }
                        }
                    }
                }


                FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
                BeanUtil.copyProperties(formDataAddGetDTO, formatExplainDTO);
                formatExplainDTO.setExplainList(explainList);
                if (Objects.nonNull(formDataAddGetDTO.getSaasSpecialParamPojo())) {
                    formatExplainDTO.setLinkBusinessType(formDataAddGetDTO.getSaasSpecialParamPojo().getLinkBusinessType());
                }
                saasAddHelp.formatExplain(formatExplainDTO);
                formDataAddGetVO.setExplainList(formatExplainDTO.getExplainList());
                // saas特殊返回字段，放在一个对象中
                saasAddHelp.formatSaasAttrToReturn(formDataAddGetVO, formDataAddGetDTO);
                explainList = formDataAddGetVO.getExplainList();
            }

            if (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode())) {
                boolean isPurchaseProductMustBelongSupplier = Objects.equals(FormConfigEnum.PURCHASE_PRODUCT_MUST_BELONG_SUPPLIER.getConfigValue(), StringConstant.POSITIVE_NUMBER);
                //可能限制供应商
                FormConfigEntity formConfigEntity = formConfigModel.getEntityByFormId(corpid, formDataAddGetDTO.getFormId(), FormConfigEnum.PURCHASE_PRODUCT_MUST_BELONG_SUPPLIER.getConfig());
                if (Objects.nonNull(formConfigEntity)) {
                    if (Objects.equals(formConfigEntity.getConfigValue(), StringConstant.POSITIVE_NUMBER)) {
                        isPurchaseProductMustBelongSupplier = true;
                    } else {
                        isPurchaseProductMustBelongSupplier = false;
                    }
                }
                JSONObject saasObj = new JSONObject();
                saasObj.put("purchaseProductBelongSupplier", isPurchaseProductMustBelongSupplier);
                formDataAddGetVO.setSaasObj(saasObj);
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                //处理账期
                fundSetService.formatPeriod(corpid, businessType, formId, explainList);
            }
            // 流水号开启严控, 对产品规格解释也添加严控字段
            if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) && strictSeri){
                for (FieldAttrEntity fieldAttrEntity : explainList) {
                    if ( Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.SPECIFICATION.getAttr())){
                        fieldAttrEntity.setStrictController(BasicConstant.ONE);
                    }
                }
            }
            // 设置关联数据和关联多选的自定义默认值
            addGetLinkDataDefault(explainList, formDataAddGetDTO, handlerExplainVO);
            formDataAddGetVO.setExplainList(explainList);
            String value = formConfigModel.getConfigValueByRedis(RedisPrefixConstant.ASSIGNMENT_RULES, corpid, formId, formDataAddGetDTO.getSaasMark(), formDataAddGetDTO.getBusinessType(), "0");
            if (StringUtil.isNotEmpty(value)) {
                formDataAddGetVO.setAssignmentRules(Integer.valueOf(value));
            }
        } catch (XbbException e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataAddGetVO;
    }

    @Override
    public LinkDataDefaultVO addGetLinkDataDefault(List<FieldAttrEntity> explainList, FormDataAddGetDTO formDataAddGetDTO, HandlerExplainVO handlerExplainVO) throws XbbException {
        List<Integer> linkDataFieldType = Arrays.asList(FieldTypeEnum.LINK_DATA.getType(), FieldTypeEnum.LINK_DATA_MULTI.getType());
        Map<String, FieldAttrEntity> linkInfoPojoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 主数据关联数据字段
        List<FieldAttrEntity> mainLinkDataFieldList = explainList.stream().filter(item ->
                linkDataFieldType.contains(item.getFieldType())
                && Objects.nonNull(item.getDefaultAttr())
                && Objects.equals(item.getDefaultAttr().getDefaultType(), DefaultTypeEnum.CUSTOM.getAlias())
                && ((Objects.equals(item.getFieldType(), FieldTypeEnum.LINK_DATA_MULTI.getType()) && item.getDefaultAttr().getDefaultValue() instanceof List && CollectionsUtil.isNotEmpty((List) item.getDefaultAttr().getDefaultValue()))
                        || (Objects.equals(item.getFieldType(), FieldTypeEnum.LINK_DATA.getType()) && item.getDefaultAttr().getDefaultValue() instanceof Map && ((Map) item.getDefaultAttr().getDefaultValue()).size() > 0)))
                .collect(Collectors.toList());
        mainLinkDataFieldList.forEach(item -> linkInfoPojoMap.put(item.getAttr(), item));

        List<FieldAttrEntity> subFormFieldList = explainList.stream().filter(item -> Objects.equals(item.getFieldType(), FieldTypeEnum.SUB_FORM.getType())).collect(Collectors.toList());
        for (FieldAttrEntity subForm : subFormFieldList) {
            String subFormAttr = subForm.getAttr();
            List<FieldAttrEntity> subFormFieldAttrList = (List<FieldAttrEntity>) subForm.getSubForm().getItems();
            // 子表单内关联数据字段
            List<FieldAttrEntity> subFormLinkDataFieldList = subFormFieldAttrList.stream().filter(item ->
                    linkDataFieldType.contains(item.getFieldType())
                    && Objects.nonNull(item.getDefaultAttr())
                    && Objects.equals(item.getDefaultAttr().getDefaultType(), DefaultTypeEnum.CUSTOM.getAlias())
                    && ((Objects.equals(item.getFieldType(), FieldTypeEnum.LINK_DATA_MULTI.getType()) && item.getDefaultAttr().getDefaultValue() instanceof List && CollectionsUtil.isNotEmpty((List) item.getDefaultAttr().getDefaultValue()))
                            || (Objects.equals(item.getFieldType(), FieldTypeEnum.LINK_DATA.getType()) && item.getDefaultAttr().getDefaultValue() instanceof Map && ((Map) item.getDefaultAttr().getDefaultValue()).size() > 0)))
                    .collect(Collectors.toList());
            subFormLinkDataFieldList.forEach(item -> linkInfoPojoMap.put(subFormAttr + StringConstant.POINT + item.getAttr(), item));
        }

        linkInfoPojoMap.forEach((attr, fieldAttr) -> {
            try {
                LinkInfoPojo linkInfoPojo = fieldAttr.getLinkInfo();
                Integer linkSaasMark = linkInfoPojo.getLinkSaasMark();
                Integer linkBusinessType = linkInfoPojo.getLinkBusinessType();
                Long linkFormId = linkInfoPojo.getLinkFormId();
                DefaultLinkInfoPojo defaultLinkInfoPojo = new DefaultLinkInfoPojo();
                if (Objects.equals(fieldAttr.getFieldType(), FieldTypeEnum.LINK_DATA.getType())) {
                    // 单选:{dataId: 1, data: {}}
                    JSONObject linkDataObj = FastJsonHelper.parseObject(JSON.toJSONString(fieldAttr.getDefaultAttr().getDefaultValue()));
                    defaultLinkInfoPojo.setDataId(linkDataObj.getLong(StringConstant.DATA_ID));
                } else {
                    // 多选:[{dataId: 1, data: {}}]
                    List<Long> linkDataIdList = new ArrayList<>();
                    JSONArray linkDataArray = FastJsonHelper.parseArray(JSON.toJSONString(fieldAttr.getDefaultAttr().getDefaultValue()));
                    for (int i = 0; i < linkDataArray.size(); i++) {
                        JSONObject linkDataObj = linkDataArray.getJSONObject(i);
                        linkDataIdList.add(linkDataObj.getLong(StringConstant.DATA_ID));
                    }
                    defaultLinkInfoPojo.setDataId(linkDataIdList);
                }
                defaultLinkInfoPojo.setFormId(linkFormId);
                defaultLinkInfoPojo.setSaasMark(linkSaasMark);
                defaultLinkInfoPojo.setBusinessType(linkBusinessType);
                LinkListPojo linkListPojo = new LinkListPojo();
                linkListPojo.setLinkAppId(linkInfoPojo.getLinkAppId());
                linkListPojo.setLinkFormId(linkFormId);
                linkListPojo.setLinkMenuId(linkInfoPojo.getLinkMenuId());
                linkListPojo.setLinkSaasMark(linkSaasMark);
                linkListPojo.setLinkBusinessType(linkBusinessType);
                linkListPojo.setAttr(attr);
                defaultLinkInfoPojo.setLinkList(linkListPojo);
                formDataAddGetDTO.setDefaultLinkInfo(defaultLinkInfoPojo);
                formDataAddGetDTO.setCustomDefault(true);
                paasFormHelp.setDefaultLinkData(explainList, formDataAddGetDTO, handlerExplainVO);
            } catch (XbbException e) {
                LOG.error("PaasFormDataServiceImpl.addGetLinkDataDefault", e);
            }
        });
        return new LinkDataDefaultVO();
    }

    /**
     * 快捷新建表单数据（需要返回表单字段描述，查重快速新建）
     *
     * @param fastAddGetDTO
     * @return
     * @throws XbbException
     */
    @Override
    public FormDataAddGetVO fastAddGet(FormDataFastAddGetDTO fastAddGetDTO) throws XbbException {
        FormDataAddGetVO formDataAddGetVO = new FormDataAddGetVO();
        String corpid = fastAddGetDTO.getCorpid();
        Integer businessType = fastAddGetDTO.getBusinessType();
        if (!Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) && !Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()) && !Objects.equals(businessType, XbbRefTypeEnum.CONTACT.getCode()) && !Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018);
        }
        // 获取解释
        PaasFormExplainEntity paasFormExplainEntity = null;
        if ( fastAddGetDTO.getFormId() != null && !Objects.equals(fastAddGetDTO.getFormId(), 0L) ) {
            paasFormExplainEntity = paasFormExplainModel.getByFormId(fastAddGetDTO.getFormId(), corpid);
        } else {
            paasFormExplainEntity = paasFormExplainModel.getByBusinessType(businessType, corpid);
        }
        if ( Objects.isNull(paasFormExplainEntity) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        FormDataAddGetDTO formDataAddGetDTO = new FormDataAddGetDTO();
        BeanUtil.copyProperties(fastAddGetDTO, formDataAddGetDTO);
        if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
            formDataAddGetDTO.setSubBusinessType(XbbRefTypeEnum.CUSTOMER.getCode());
            BeanUtil.copyProperties(paasFormExplainEntity, formDataAddGetDTO);
            formDataAddGetVO = addGet(formDataAddGetDTO);
            List<FieldAttrEntity> explainList = formDataAddGetVO.getExplainList();
            explainList.forEach((item) -> {
                if ( Objects.equals(item.getAttr(), CustomerManagementEnum.NAME.getAttr()) ) {
                    if ( Objects.equals(fastAddGetDTO.getDefaultAttr(), CustomerManagementEnum.NAME.getSaasAttr()) ) {
                        item.setDefaultAttr(saasUpdateHelp.setDefaultValue(fastAddGetDTO.getDefaultValue()));
                    }
                } else if ( Objects.equals(item.getAttr(), CustomerManagementEnum.PHONE.getAttr()) ) {
                    if ( Objects.equals(fastAddGetDTO.getDefaultAttr(), CustomerManagementEnum.PHONE.getSaasAttr()) ) {
                        JSONArray phoneArray = new JSONArray();
                        JSONObject phoneObject = new JSONObject();
                        phoneObject.put(StringConstant.PHONE_TYPE_ATTR,"1");
                        phoneObject.put(StringConstant.PHONE_TEL_ATTR,fastAddGetDTO.getDefaultValue());
                        phoneArray.add(phoneObject);
                        item.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(phoneArray));
                    }
                }
            });
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CONTACT.getCode())) {
            BeanUtil.copyProperties(paasFormExplainEntity, formDataAddGetDTO);
            formDataAddGetVO = addGet(formDataAddGetDTO);
            List<FieldAttrEntity> explainList = formDataAddGetVO.getExplainList();
            explainList.forEach((item) -> {
                if ( Objects.equals(item.getAttr(), ContactEnum.NAME.getAttr()) ) {
                    if ( Objects.equals(fastAddGetDTO.getDefaultAttr(), ContactEnum.NAME.getSaasAttr()) ) {
                        item.setDefaultAttr(saasUpdateHelp.setDefaultValue(fastAddGetDTO.getDefaultValue()));
                    }
                } else if ( Objects.equals(item.getAttr(), ContactEnum.PHONE.getAttr()) ) {
                    if ( Objects.equals(fastAddGetDTO.getDefaultAttr(), ContactEnum.PHONE.getSaasAttr()) ) {
                        JSONArray phoneArray = new JSONArray();
                        JSONObject phoneObject = new JSONObject();
                        phoneObject.put(StringConstant.PHONE_TYPE_ATTR,"1");
                        phoneObject.put(StringConstant.PHONE_TEL_ATTR,fastAddGetDTO.getDefaultValue());
                        phoneArray.add(phoneObject);
                        item.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(phoneArray));
                    }
                }
            });
        } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
            formDataAddGetDTO.setSubBusinessType(XbbRefTypeEnum.ALL_CLUE.getCode());
            BeanUtil.copyProperties(paasFormExplainEntity, formDataAddGetDTO);
            formDataAddGetVO = addGet(formDataAddGetDTO);
            List<FieldAttrEntity> explainList = formDataAddGetVO.getExplainList();
            explainList.forEach((item) -> {
                if ( Objects.equals(item.getAttr(), ClueEnum.COMPANY_NAME.getAttr()) ) {
                    if ( Objects.equals(fastAddGetDTO.getDefaultAttr(), ClueEnum.COMPANY_NAME.getSaasAttr()) ) {
                        item.setDefaultAttr(saasUpdateHelp.setDefaultValue(fastAddGetDTO.getDefaultValue()));
                    }
                } else if ( Objects.equals(item.getAttr(), ClueEnum.PHONE.getAttr()) ) {
                    if ( Objects.equals(fastAddGetDTO.getDefaultAttr(), ClueEnum.PHONE.getSaasAttr()) ) {
                        JSONArray phoneArray = new JSONArray();
                        JSONObject phoneObject = new JSONObject();
                        phoneObject.put(StringConstant.PHONE_TYPE_ATTR,"1");
                        phoneObject.put(StringConstant.PHONE_TEL_ATTR,fastAddGetDTO.getDefaultValue());
                        phoneArray.add(phoneObject);
                        item.setDefaultAttr(saasUpdateHelp.getDefaultAttrPojo(phoneArray));
                    }
                }
            });
        } else {
            //机会
            formDataAddGetDTO.setSubBusinessType(XbbRefTypeEnum.ALL_OPPORTUNITY.getCode());
            BeanUtil.copyProperties(paasFormExplainEntity, formDataAddGetDTO);
            formDataAddGetVO = addGet(formDataAddGetDTO);
            List<FieldAttrEntity> explainList = formDataAddGetVO.getExplainList();
            explainList.forEach((item) -> {
                if ( Objects.equals(item.getAttr(), SalesOpportunityEnum.NAME.getAttr()) ) {
                    if ( Objects.equals(fastAddGetDTO.getDefaultAttr(), SalesOpportunityEnum.NAME.getSaasAttr()) ) {
                        item.setDefaultAttr(saasUpdateHelp.setDefaultValue(fastAddGetDTO.getDefaultValue()));
                    }
                }
            });
        }
        return formDataAddGetVO;
    }

    @Override
    public FormDataUpdateGetVO updateGet(FormDataUpdateGetDTO formDataUpdateGetDTO) throws XbbException {
        BusinessEditPageRenderService businessEditPageRenderService = businessEditPageRenderMap.get(formDataUpdateGetDTO.getBusinessType());
        if (Objects.nonNull(businessEditPageRenderService) && !Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), formDataUpdateGetDTO.getDistributorMark())) {
            return businessEditPageRenderService.updateGet(formDataUpdateGetDTO);
        }
        if ( Objects.equals(formDataUpdateGetDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) ) {
            // 产品编辑的时候一定要传父产品的id
            PaasFormDataEntityExt productEntity = saasGetHelp.getFormData(formDataUpdateGetDTO.getDataId(), formDataUpdateGetDTO.getCorpid(), XbbRefTypeEnum.PRODUCT.getCode());
            if ( productEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            JSONObject productData = productEntity.getData();
            Long parentId = productData.getLong(ProductEnum.PARENT_ID.getAttr());
            if ( !Objects.equals(parentId, 0L) ) {
                formDataUpdateGetDTO.setDataId(parentId);
            }
        }
        //作废的发票编辑时，提示不允许编辑
        boolean invoiceFlag = Objects.equals(formDataUpdateGetDTO.getBusinessType(), XbbRefTypeEnum.INVOICE.getCode()) ||
                Objects.equals(formDataUpdateGetDTO.getBusinessType(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode());
        if(invoiceFlag){
            Long dataId = formDataUpdateGetDTO.getDataId();
            PaasFormDataEntityExt formData = saasUpdateHelp.getFormData(dataId, formDataUpdateGetDTO.getCorpid(), formDataUpdateGetDTO.getBusinessType());
            if (Objects.isNull(formData)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            Integer isCancel = 0;
            if(Objects.equals(formDataUpdateGetDTO.getBusinessType(), XbbRefTypeEnum.INVOICE.getCode())){
                isCancel = FastJsonHelper.getIntegerOrDefaultFromFormData(formData.getData(), InvoiceEnum.IS_CANCEL.getAttr(), IsCancelEnum.NOT_CANCEL.getCode());

            }else if(Objects.equals(formDataUpdateGetDTO.getBusinessType(), XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                isCancel = FastJsonHelper.getIntegerOrDefaultFromFormData(formData.getData(), PurchaseInvoiceEnum.IS_CANCEL.getAttr(), IsCancelEnum.NOT_CANCEL.getCode());
            }
            if (Objects.equals(BasicConstant.ONE, isCancel)){
                //是作废的发票，提示作废发票不允许编辑
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.INVOICE_CANCEL_NOT_EDIT);
            }
        }

         FormDataUpdateGetVO formDataUpdateGetVO = new FormDataUpdateGetVO();
        try {
            VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO();
            BeanUtil.copyProperties(formDataUpdateGetDTO, verifyUpdatePermissionDTO);
            SaasSpecialParamPojo saasSpecialParamPojo = formDataUpdateGetDTO.getSaasSpecialParamPojo();
            //新版本,复制跳过编辑权限校验
            Boolean quotationBoolean = false;
            if ( !Objects.equals(formDataUpdateGetDTO.getNewVersionAttr(), null) ) {
                quotationBoolean = formDataUpdateGetDTO.getNewVersionAttr();
            }
            if ( quotationBoolean || (Objects.nonNull(saasSpecialParamPojo) && Objects.equals(saasSpecialParamPojo.getFromCopy(), BasicConstant.ONE)) ) {

            } else {
                ProPermissionHelp.verifyEditPermission(verifyUpdatePermissionDTO);
            }
            Integer saasMark = formDataUpdateGetDTO.getSaasMark();
            //先获取data数据
            String corpid = formDataUpdateGetDTO.getCorpid();
            Integer distributorMark = formDataUpdateGetDTO.getDistributorMark();
            Long formDataId = formDataUpdateGetDTO.getDataId();
            Long menuId = formDataUpdateGetDTO.getMenuId();
            UserVO loginUser = formDataUpdateGetDTO.getLoginUser();
            Long formId = formDataUpdateGetDTO.getFormId();
            PaasFormDataEntityExt formData;
            Integer businessType = formDataUpdateGetDTO.getBusinessType();
            LowCodeConfigGetDTO lowCodeConfigGetDTO = new LowCodeConfigGetDTO();
            lowCodeConfigGetDTO.setCorpid(corpid);
            lowCodeConfigGetDTO.setFormId(formDataUpdateGetDTO.getFormId());
            lowCodeConfigGetDTO.setBusinessType(businessType);
            lowCodeConfigGetDTO.setLoginUser(loginUser);
            lowCodeConfigGetDTO.setType(ButtonTypeEnum.EDIT.getCode());
            LowCodeConfigGetVO lowCodeConfig = lowCodeConfigService.get(lowCodeConfigGetDTO);
            formDataUpdateGetVO.setLowCodeConfig(lowCodeConfig);
            if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                formDataUpdateGetVO = workOrderFormDataService.updateGet(formDataUpdateGetDTO);
                formDataUpdateGetVO.setLowCodeConfig(lowCodeConfig);
                return formDataUpdateGetVO;
            }
            formData = formDataHelp.getFormDataWithTeam(corpid, saasMark, businessType, formDataId);
            if (Objects.isNull(formData) || Objects.isNull(formData.getId())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            //拼装富文本数据
            richTextService.addRichTextByDataId(formDataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL.getDel(), formData.getData());
            // JXC改造：编辑时新加字段老数据回显
            saasUpdateHelp.formOldData(formData,businessType);
            if (Objects.equals(formData.getDel(),DelEnum.DELETE.getDel())) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);

            }
            if (FlowStatusEnum.inApproval(formData.getFlowStatus()) && !Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode())) {
                throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200020);
            }
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formData.getFormId(), corpid);
            if ( paasFormEntityExt == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            boolean formCopy = Objects.nonNull(saasSpecialParamPojo) && Objects.equals(saasSpecialParamPojo.getFromCopy(), BasicConstant.ONE);
            boolean isOpenWorkflow = commonHelp.isOpenWorkFlow(corpid);

            boolean newVersionAndUpdate = Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) && !(Objects.nonNull(saasSpecialParamPojo) && Objects.equals(saasSpecialParamPojo.getFromCopy(), BasicConstant.ONE) && !Objects.equals(saasSpecialParamPojo.getNewVersion(), BasicConstant.ONE));
            if ( newVersionAndUpdate && !isOpenWorkflow) {
                // 报价单编辑/新版本需要判断是否有新版本在审批中，复制不需要
                String groupNumber = FastJsonHelper.getStringOrDefaultFromFormData(formData.getData(), QuotationEnum.GROUP_NUMBER.getAttr(), "");
                List<PaasProcessDataEntity> entities = paasProcessDataModel.getInApprovalData(XbbRefTypeEnum.QUOTATION.getCode(), QuotationEnum.GROUP_NUMBER.getAttr(), groupNumber, corpid);

                if ( entities != null && entities.size() > 0L ) {
                    throw new XbbException(QuotationErrorCodeEnum.API_ERROR_246009);
                }
            }

            saasAddHelp.handleFormEntity(paasFormEntityExt, formDataUpdateGetDTO.getSaasMark(), formDataUpdateGetDTO.getBusinessType());
            formDataUpdateGetVO.setPaasFormEntity(paasFormEntityExt);

            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formData.getFormId(), corpid);
            if ( paasFormExplainEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            if (!formCopy) {
                // 来自复制的不判断该逻辑
                // 是否可以编辑
                boolean isEdit;
                if (isOpenWorkflow) {
                    isEdit = workflowFormDataOperationService.isApprovedEdit(paasFormEntityExt.getId(), corpid, paasFormEntityExt.getSaasMark(), paasFormEntityExt.getBusinessType(), formData.getFlowStatus(), loginUser);
                } else {
                    isEdit = paasProcessTemplateModel.isApprovedEdit(formDataUpdateGetDTO.getAppId(), menuId, formDataUpdateGetDTO.getFormId(), loginUser, formData);
                }
                if ( !isEdit ) {
                    throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200017);
                }
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(paasFormExplainEntity.getExplains());
                FormDataDetailDTO formDataDetailDTO = new FormDataDetailDTO(formDataId, saasMark, businessType, menuId, formData.getCreatorId(), loginUser);
                verifyUpdatePermissionDTO.setPaasFormDataEntityExt(formData);
                boolean hasDataPermission = commonPermissionHelp.checkEditPermission(formDataDetailDTO, verifyUpdatePermissionDTO, explainMap);
                if (!hasDataPermission){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050.getCode(), String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), OperateTypeEnum.EDIT.getName()));
                }
                commonPermissionHelp.removeConvertedData(formData.getData());
            }
            // fix: 20682 【成功部】移动端周报统计数据没出来，电脑上正常
            if ( Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), businessType) ) {
                if (!Objects.equals(formDataUpdateGetDTO.getUserId(), formData.getCreatorId())) {
                    // 自己只能编辑自己的工作报告
                    throw new XbbException(WorkReportErrorCodeEnum.API_ERROR_207024);
                }
                formDataUpdateGetDTO.setSubBusinessType(paasFormEntityExt.getBusinessType());
            }
            // 获取字段解释信息，并且过滤不可见字段
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);

            // ---- 获取用户和部门容器start
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(formDataUpdateGetDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(formDataUpdateGetVO.getExplainList());
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
//            Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//            Map<String, DepartmentEntity> departmentMap = commonHelp.getDepMap(userAndDepartmentGetDTO);
            // ---- 获取用户和部门容器end
            //根据套餐判断负责人属性
            Integer feeType = commonHelp.getCurrentCompanyPackage(corpid);
            boolean ultimateTag = Objects.equals(feeType, PackageTypeEnum.ULTIMATE.getType());
            if(!ultimateTag && FormOwnerUniqueEnum.getDefaultBusinessList().contains(businessType)){
                //只有旗舰版支持负责人唯一设置，其他版本拿默认设置
                FormOwnerUniqueEnum formOwnerUniqueEnum = FormOwnerUniqueEnum.getFormOwnerUniqueByBus(businessType);
                Integer multiple = formOwnerUniqueEnum.getValue();
                for (FieldAttrEntity fieldAttrEntity : explainList) {
                    if(Objects.equals(fieldAttrEntity.getAttr(),FieldTypeEnum.OWNERID.getAlias())){
                        fieldAttrEntity.setMultiple(multiple);
                    }
                }
            }
            //确认是否为创建回款单
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
            boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
            if (sheetFlag) {
                //如果是回/付款单，则根据数据data内的回/付款单类型重置sheetTypeEnum（前端传过来的businessType可能没有详细区分哪种类型回/付款单）
                sheetTypeEnum = fundHelp.getSheetTypeEnumByData(sheetTypeEnum, formData.getData());
                fundHelp.handlePaymentSheet(false, sheetTypeEnum, explainList, corpid, distributorMark);
            }
            /*if (Objects.equals(formDataUpdateGetDTO.getIsOuterLink(), BasicConstant.ONE)) {
                handoverOuterLink(corpid, explainList, paasFormEntityExt.getId());
            }*/
            if (Objects.equals(formDataUpdateGetDTO.getIsOuterLink(), BasicConstant.ONE)) {
                // 外链分享页编辑按钮跳转到系统编辑页面需要传这个参数
                if (Objects.isNull(saasSpecialParamPojo)) {
                    saasSpecialParamPojo = new SaasSpecialParamPojo();
                }
                saasSpecialParamPojo.setFromEdit(BasicConstant.ONE);
                formDataUpdateGetDTO.setSaasSpecialParamPojo(saasSpecialParamPojo);
            }
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataUpdateGetDTO, handlerExplainDTO, false);
            handlerExplainDTO.setExplainList(explainList);
            handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);

            // 获取协同人和负责人
            paasFormHelp.getOwnerIdAndCoUserId(handlerExplainDTO, saasMark, businessType, formDataUpdateGetDTO.getSubBusinessType(), formData, userMap);
            List<String> ownerIds = handlerExplainDTO.getOwnerId();
            List<String> coUserIds = handlerExplainDTO.getCoUserId();
            formData.getData().put(FieldTypeEnum.OWNERID.getAlias(), ownerIds);
            formData.getData().put(FieldTypeEnum.COUSERID.getAlias(), coUserIds);
            //校验数据编辑权限(团队权限&共享权限)
            validateDataEditPermission(formDataUpdateGetDTO, explainList, formData);
            List<ReturnUserAndDepartmentPojo> ownerIdPojoList = new ArrayList<>();
            List<ReturnUserAndDepartmentPojo> coUserIdPojoList = new ArrayList<>();
            if ( !Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType) && !Objects.equals(XbbRefTypeEnum.COMPETITOR.getCode(), businessType) ) {
                ownerIds.forEach(owner -> {
                    UserEntity userEntity = userMap.get(owner);
                    if ( Objects.nonNull(userEntity) ) {
                        ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                        BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
                        returnUserAndDepartmentPojo.setId(userEntity.getUserId());
                        ownerIdPojoList.add(returnUserAndDepartmentPojo);
                    }
                });
                coUserIds.forEach(coUser -> {
                    UserEntity userEntity = userMap.get(coUser);
                    if ( Objects.nonNull(userEntity) ) {
                        ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                        BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
                        returnUserAndDepartmentPojo.setId(userEntity.getUserId());
                        coUserIdPojoList.add(returnUserAndDepartmentPojo);
                    }
                });
            } else {
                UserEntity userEntity = userMap.get(formData.getOwnerId());
                if ( Objects.nonNull(userEntity) ) {
                    ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                    BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
                    returnUserAndDepartmentPojo.setId(userEntity.getUserId());
                    ownerIdPojoList.add(returnUserAndDepartmentPojo);
                }
            }
            handlerExplainDTO.setFormData(formData.getData());
            HandlerExplainVO handlerExplainVO = new HandlerExplainVO();
            if ( Objects.nonNull(saasSpecialParamPojo) && Objects.equals(saasSpecialParamPojo.getFromCopy(), BasicConstant.ONE) ) {
                // 详情点击“复制”会调用此处渲染
                handlerExplainVO = formDataAddFormExplainHandlerName.handleExplain(handlerExplainDTO);
            } else {
                handlerExplainVO = formDataUpdateGetExplainHandler.handleExplain(handlerExplainDTO);
            }
            if ( handlerExplainVO == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            proDetailHandlerHelp.handelSaasSpecialUpdate(handlerExplainVO.getHeadList(), formDataUpdateGetDTO.getBusinessType(), formData, formCopy,distributorMark);
            List<FieldAttrEntity> headList = handlerExplainVO.getHeadList();
            // 查询客户名称和电话判重设置
            if ( Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                handlerCustomerRepeat(corpid, formDataUpdateGetDTO.getFormId(), headList, businessType);
            }

            if ((Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode()))
                    &&CollectionsUtil.isNotEmpty(headList)) {
                headList.forEach(e->{
                    if (Objects.equals(e.getAttr(), PaasStageEnum.STAGE_RATIO.getAttr())){
                        e.setAccuracy(0);
                    }
                });
            }
            // 工作报告统计数据从解释中取
            if (Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode())) {
                FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, formatExplainDTO);
                formatExplainDTO.setExplainList(headList);
                saasAddHelp.formatExplain(formatExplainDTO);
                headList = formatExplainDTO.getExplainList();
            }

            formDataUpdateGetVO.setExplainList(headList);

            // 查看是否能使用精线索的工商模糊查询
            if (fineClueHelp.isBusinessSearch(corpid, businessType, distributorMark)) {
                formDataUpdateGetVO.setIsFineClue(1);
            }
            // 是否有关联查询
            boolean hasLinkSearch = false;
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            for ( FieldAttrEntity fieldAttrEntity : formDataUpdateGetVO.getExplainList() ) {
                // 存放字段容器
                explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
                if ( FieldTypeEnum.LINK_QUERY.getType().equals(fieldAttrEntity.getFieldType()) ) {
                    hasLinkSearch = true;
                } else if ( FieldTypeEnum.SUB_FORM.getType().equals(fieldAttrEntity.getFieldType()) ) {
                    List<? extends FieldAttrEntity> fieldList = fieldAttrEntity.getSubForm().getItems();
                    if ( Objects.isNull(fieldList) ) {
                        continue;
                    }
                    for ( FieldAttrEntity subField : fieldList ) {
                        if ( FieldTypeEnum.LINK_QUERY.getType().equals(subField.getFieldType()) ) {
                            hasLinkSearch = true;
                            break;
                        }
                    }
                }
            }
            //如果是联系人业务编辑的时候需要判断一下这个人有没有相关权限，参考需求文档https://alidocs.dingtalk.com/i/nodes/yZvMRzlLwOAWrRxabOXOWnjY02pBqGox?nav=spaces&navQuery=spaceId%3DO5pXBWER2q4lym7Z
            /*if (Objects.equals(XbbRefTypeEnum.CONTACT.getCode(), formDataUpdateGetDTO.getBusinessType())) {
                FormDataDetailDTO formDataDetailDTO = new FormDataDetailDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, formDataDetailDTO);
                //首先需要判断有没有联系人的数据权限
                boolean checkPermission = saasDetailPermissionHelp.checkPermission(formData, formDataUpdateGetDTO.getLoginUser(), formDataUpdateGetDTO.getLoginUser().getDepSet(),
                        XbbRefTypeEnum.CONTACT.getCode());
                if (!checkPermission) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050, String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), UpdateProPermissionAliasEnum.CONTACT_UPDATE.getMemo()));
                }
                boolean editPer = userTeamHelp.teamMembersCheckEditPermission(formDataDetailDTO, explainMap);
                if (!editPer) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050, String.format(SystemErrorCodeEnum.API_ERROR_100050.getMsg(), UpdateProPermissionAliasEnum.CONTACT_UPDATE.getMemo()));
                }
            }*/
            JSONObject data = formData.getData();
            if (Objects.equals(formDataUpdateGetDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode())) {
                SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, saasAnalysisDataDTO);
                // saas特殊格式转换
                saasAnalysisDataDTO.setExplainMap(explainMap);
                saasUpdateHelp.formatData(saasAnalysisDataDTO, data);
                formatProductHelp.formatProduct(saasAnalysisDataDTO,data,explainList,formCopy);

                if (formDataUpdateGetDTO.getIsCopy() && data.containsKey(BasicConstant.OFF_LINED_PRODUCTS) && ((ArrayList<String>)data.get(BasicConstant.OFF_LINED_PRODUCTS)).size() != 0){
                    // 有下架产品, fix:修复多个产品下架只显示一个
                    JSONArray offlinedProducts = data.getJSONArray(BasicConstant.OFF_LINED_PRODUCTS);
                    int count = offlinedProducts.size();
                    //fix bug  34227
                    String productName = offlinedProducts.stream().filter(Objects::nonNull).map(Object::toString).collect(Collectors.joining(" "));
                    formDataUpdateGetVO.setCopyConfirm(String.format(I18nMessageUtil.getMessage(StringConstant.COPY_CONFIRM), productName, count, XbbRefTypeEnum.getByCode(businessType).getName()));
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_COMMUNICATE.getCode())) {
                    if (data.containsKey(CustomerCommunicateEnum.AT_USERNAME.getAttr())) {
                        JSONArray jsonArray = data.getJSONArray(CustomerCommunicateEnum.AT_USERNAME.getAttr());
                        if (jsonArray.size() <= 0) {
                            data.remove(CustomerCommunicateEnum.AT_USERNAME.getAttr());
                        }
                    }
                } else if (data.containsKey(SupplierCommunicateEnum.AT_USERNAME.getAttr())) {
                    if (data.containsKey(SupplierCommunicateEnum.AT_USERNAME.getAttr())) {
                        JSONArray jsonArray = data.getJSONArray(SupplierCommunicateEnum.AT_USERNAME.getAttr());
                        if (jsonArray.size() <= 0) {
                            data.remove(SupplierCommunicateEnum.AT_USERNAME.getAttr());
                        }
                    }
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                    //处理账期
                    fundSetService.formatPeriod(corpid, businessType, formDataUpdateGetDTO.getFormId(), explainList);
                }

                if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_PURCHASE.getCode())) {
                    //编辑时对退货退款或采购退货中作废/红冲发票以及关联红冲回/付款单的回显处理
                    formatInvoiceAndSheetInRefund(data, corpid, formDataUpdateGetDTO, businessType);
                } else if (RedundantTemplateTypeEnum.isMultiTemplate(businessType) && !Objects.equals(paasFormEntityExt.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    // 合同，客户模板选择,编辑回显，我不想加的，凤娇一定要
                    TemplateDTO templateDTO = new TemplateDTO();
                    BeanUtil.copyProperties(formDataUpdateGetDTO, templateDTO);
                    templateDTO.setSubBusinessType(templateDTO.getBusinessType());
                    List<EnablePojo> saasTemplateList = templateService.getSaasTemplateList(templateDTO);

                    FieldAttrEntity templateFieldAttrEntity = new FieldAttrEntity();
                    if ( saasTemplateList.size() == 1 ) {
                        templateFieldAttrEntity.setVisible(0);
                    } else {
                        templateFieldAttrEntity.setVisible(1);
                    }
                    if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                        templateFieldAttrEntity.setAttrName("客户模板");
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) ){
                        templateFieldAttrEntity.setAttrName("合同模板");
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
                        templateFieldAttrEntity.setAttrName("机会模板");
                    } else if (Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                        templateFieldAttrEntity.setAttrName("线索模板");
                    }
                    templateFieldAttrEntity.setAttr(FieldTypeEnum.TEMPLATE.getAlias());
                    templateFieldAttrEntity.setAttrType(FieldTypeEnum.TEMPLATE.getEsalias());
                    templateFieldAttrEntity.setFieldType(FieldTypeEnum.TEMPLATE.getType());
                    templateFieldAttrEntity.setEditable(0);
                    templateFieldAttrEntity.setComboType(0);
                    List<ItemPoJo> templateItem = new ArrayList<>();
                    ItemPoJo itemPoJo = new ItemPoJo();
                    itemPoJo.setValue(paasFormEntityExt.getId());
                    itemPoJo.setText(paasFormEntityExt.getName());
                    itemPoJo.setChecked(true);
                    templateItem.add(itemPoJo);
                    templateFieldAttrEntity.setItems(templateItem);
                    formDataUpdateGetVO.getExplainList().add(0, templateFieldAttrEntity);

                    data.put(FieldTypeEnum.TEMPLATE.getAlias(), paasFormEntityExt.getId());
                }


                // 编辑时saas字段显示特殊逻辑
                FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, formatExplainDTO);
                formatExplainDTO.setExplainList(formDataUpdateGetVO.getExplainList());
                formatExplainDTO.setDataEntity(formData);
                formatExplainDTO.setResult(data);
                formatExplainDTO.setFromCopy(formCopy);
//                saasUpdateHelp.formatExplain(formatExplainDTO);
                // 盘点调拨当有下游单据在审批中时，不允许编辑产品
                if (Objects.equals(businessType, XbbRefTypeEnum.INVENTORY.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.TRANSFER.getCode())) {
                    if (isOpenWorkflow) {
                        BoolQueryBuilder boolQueryBuilder = boolQuery();
                        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                        boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                        boolQueryBuilder.filter(termQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.REF_ID), formDataId));
                        Integer type = OutstockTypeEnum.getByBuisenssTypeInt(businessType);
                        boolQueryBuilder.filter(termQuery(OutstockEnum.getEsAttr4Keyword(OutstockEnum.TYPE), type));
                        boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
                        long outstockCount = paasEsModel.count(boolQueryBuilder, IndexTypeEnum.IDX_SAAS_OUTSTOCK);
                        BoolQueryBuilder instockBoolQueryBuilder = boolQuery();
                        instockBoolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
                        instockBoolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                        instockBoolQueryBuilder.filter(termQuery(InstockEnum.getEsAttr4Keyword(InstockEnum.REF_ID), formDataId));
                        Integer instockType = InstockTypeEnum.getByBuisenssTypeInt(businessType);
                        instockBoolQueryBuilder.filter(termQuery(InstockEnum.getEsAttr4Keyword(InstockEnum.TYPE), instockType));
                        instockBoolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
                        long instockCount = paasEsModel.count(instockBoolQueryBuilder, IndexTypeEnum.IDX_SAAS_INSTOCK);
                        if (outstockCount> 0 || instockCount > 0) {
                            formatExplainDTO.setHasSheetInApproval(true);
                        }
                    } else {
                        Map<String,Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        param.put(StringConstant.CORPID,corpid);
                        param.put(StringConstant.DEL,DelEnum.NORMAL.getDel());
                        param.put("firstRefId", formDataId);
                        param.put("formDataId", 0);
                        param.put("businessTypeIn", Arrays.asList(XbbRefTypeEnum.OTHER_OUTSTOCK.getCode(), XbbRefTypeEnum.OTHER_INSTOCK.getCode()));
                        param.put("flowStatusIn", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
                        param.put("sourceBusinessType", businessType);
                        param.put("moduleType", 1);
                        List<PaasProcessRelatedDataEntity> paasProcessRelatedDataList = paasProcessRelatedDataModel.findEntitys(param);
                        if (!paasProcessRelatedDataList.isEmpty()) {
                            formatExplainDTO.setHasSheetInApproval(true);
                        }
                    }

                }
                // 工作报告的统计数据，需要从解释里取
                if (Objects.equals(businessType, XbbRefTypeEnum.WORK_REPORT.getCode())) {
                    Map<String, FieldAttrEntity> statisticsMap = ExplainUtil.getExplainMapByList(formatExplainDTO.getExplainList(), WorkReportFieldEnum.THIS_STATISTIC.getAttr());
                    FieldAttrEntity attrEntity = statisticsMap.get(WorkReportFieldEnum.THIS_STATISTIC.getAttr());
                    if (Objects.nonNull(attrEntity)) {
                        DefaultAttrPoJo statisticsPojo = attrEntity.getDefaultAttr();
                        Object value = statisticsPojo.getDefaultValue();
                        data.put(WorkReportFieldEnum.THIS_STATISTIC.getAttr(), value);
                    }
                }
                formExplainHelp.formatExplain(formatExplainDTO, data);
                // saas特殊返回字段，放在一个对象中
                saasUpdateHelp.formatSaasAttrToReturn(formDataUpdateGetVO, formDataUpdateGetDTO.getBusinessType(), data);
                formDataUpdateGetVO.setSaasSpecialParamPojo(formatExplainDTO.getSaasSpecialParamPojo());
            }
            if (XbbRefTypeEnum.hasVisibleRangeBusiness().contains(businessType)) {
                data.put(VisibleRangeEnum.VISIBLE_DEPT.getAttr(), ownerIds);
                data.put(VisibleRangeEnum.VISIBLE_USER.getAttr(), coUserIds);
                data.put(FieldTypeEnum.OWNERID.getAlias(), ownerIdPojoList);
            } else if(Objects.equals(XbbRefTypeEnum.COMPETITOR.getCode(), businessType)){
                data.put(CompetitorEnum.VISBLE_DEPT.getAttr(), ownerIds);
                data.put(CompetitorEnum.VISBLE_USER.getAttr(), coUserIds);
            } else {
                boolean customerPubicBus = Objects.equals(formDataUpdateGetDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) &&
                        Objects.equals(data.getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr()), 1);
                boolean clueOrClueBus = Objects.equals(formDataUpdateGetDTO.getBusinessType(), XbbRefTypeEnum.CLUE.getCode()) &&
                        Objects.equals(data.getInteger(ClueEnum.IS_PUBLIC.getAttr()), 1);
                data.put(FieldTypeEnum.OWNERID.getAlias(), ownerIdPojoList);
                data.put(FieldTypeEnum.COUSERID.getAlias(), coUserIdPojoList);
                if (customerPubicBus || clueOrClueBus) {
                    data.put(FieldTypeEnum.OWNERID.getAlias(), new ArrayList<>());
                    data.put(FieldTypeEnum.COUSERID.getAlias(), new ArrayList<>());
                }
            }
            data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), formData.getDepartmentId());
            data.put(FieldTypeEnum.SERIALNO.getAlias(), formData.getSerialNo());
            // 解析数据信息
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            BeanUtil.copyProperties(formDataUpdateGetDTO, parseSingleRowDataDTO);
            parseSingleRowDataDTO.setDataJsonObject(data);
            parseSingleRowDataDTO.setExplainMap(explainMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            ParseSingleRowDataVO parseSingleRowDataVO = formDataUpdateGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
            if ( parseSingleRowDataVO == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
            }
            LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
            JSONObject result = parseSingleRowDataVO.getResult();
            Map<String, PaasFormExplainEntity> formExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            // 获取关联数据的信息
            if ( linkResultDataVO != null && !linkResultDataVO.getLinkData().isEmpty() && !linkResultDataVO.getLinkDataSet().isEmpty() ) {
                FormDataGetDTO formDataGetDTO = new FormDataGetDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, formDataGetDTO);
                linkResultDataVO.setData(result);
                linkResultDataVO.setExplainMap(explainMap);
                linkResultDataVO.setUserMap(userMap);
                linkResultDataVO.setDepartmentMap(departmentMap);
                linkResultDataVO.setExplainList(explainList);
                result = formDataLinkDataUpdateGetService.formDataLinkDataGet(formDataUpdateGetDTO, linkResultDataVO);
                formExplainMap = linkResultDataVO.getFormExplainMap();
            }
            // 获取关联查询 小鲍那货要自己解析，所以我只能注释掉
//            if (hasLinkSearch) {
//                LinkSearchGetDTO linkSearchGetDTO = new LinkSearchGetDTO();
//                BeanUtil.copyProperties(formDataUpdateGetDTO, linkSearchGetDTO);
//                linkSearchGetDTO.setDepartmentMap(departmentMap);
//                linkSearchGetDTO.setUserMap(userMap);
//                linkSearchGetDTO.setJsonObject(result);
//                linkSearchGetDTO.setExplainMap(explainMap);
//                linkSearchGetDTO.setFormExplainMap(formExplainMap);
//                LinkSearchGetVO linkSearchGetVO = formDataLinkSearchUpdateGetService.formDataLinkDataGet(linkSearchGetDTO);
//                if (Objects.isNull(linkSearchGetVO)) {
//                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.LINK_SEARCH_FAILED);
//                }
//                result = linkSearchGetVO.getResult();
//            }
            if ( Objects.equals(businessType, XbbRefTypeEnum.INVOICE.getCode()) ) {
                invoiceCommonHelper.getUpdateDataBySalesInvoice(formDataUpdateGetDTO,null,saasSpecialParamPojo,formData,result,formDataUpdateGetVO.getExplainList());
//                fundHelp.setInvoiceNotEditToExplain(formDataUpdateGetVO.getExplainList(),fromRed,isRed,businessType);
            }
            if(Objects.equals(businessType, XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                invoiceCommonHelper.getUpdateDataByPurchaseInvoice(formDataUpdateGetDTO,null,saasSpecialParamPojo,formData,result,explainList);
//                fundHelp.setInvoiceNotEditToExplain(formDataUpdateGetVO.getExplainList(),purchaseInvoiceAmountDetailGetDTO.getFormRed(),purchaseInvoiceAmountDetailGetDTO.getIsRed(),businessType);
            }
            if (sheetFlag) {
                JSONArray amountDetail = getAmountDetail4exist(sheetTypeEnum, parseSingleRowDataDTO, corpid, formDataId, formData);
                result.put(PaasConstant.AMOUNTDETAIL, amountDetail);
            }
            //现在前端只需要计算重复金额：重复金额为回款计划的已收款部分
            if ( Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode())) {
                Double writeOffAmount = 0D;
                if ( !formDataUpdateGetDTO.getIsCopy() ) {
                    writeOffAmount = fundMoneyHelp.getCoverCalAmount(formDataUpdateGetDTO,explainMap,businessType);
                }
                formDataUpdateGetVO.setWriteOffAmount(writeOffAmount);
            }
            if(Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode())){
                boolean isPurchaseProductMustBelongSupplier = Objects.equals(FormConfigEnum.PURCHASE_PRODUCT_MUST_BELONG_SUPPLIER.getConfigValue(), StringConstant.POSITIVE_NUMBER);
                //可能限制供应商
                FormConfigEntity formConfigEntity = formConfigModel.getEntityByFormId(corpid,formDataUpdateGetDTO.getFormId(), FormConfigEnum.PURCHASE_PRODUCT_MUST_BELONG_SUPPLIER.getConfig());
                if (Objects.nonNull(formConfigEntity)) {
                    if (Objects.equals(formConfigEntity.getConfigValue(), StringConstant.POSITIVE_NUMBER)) {
                        isPurchaseProductMustBelongSupplier = true;
                    } else {
                        isPurchaseProductMustBelongSupplier = false;
                    }
                }
                JSONObject saasObj = new JSONObject();
                saasObj.put("purchaseProductBelongSupplier", isPurchaseProductMustBelongSupplier);
                formDataUpdateGetVO.setSaasObj(saasObj);
            }
            formData.setData(result);
            //精线索工商查询 通过pid控制icon显示
            if(fineClueHelp.hasBusinessSearch(businessType)){
                String companyName = result.getString(ManagementBaseEnum.NAME.getAttr());
                String pid = fineClueHelp.getPidByCompanyName(corpid, companyName ,formDataUpdateGetDTO.getPlatform());
                if (Objects.nonNull(pid)) {
                    formData.setPid(pid);
                }
            }
            formDataUpdateGetVO.setData(formData);
            String value = formConfigModel.getConfigValueByRedis(RedisPrefixConstant.ASSIGNMENT_RULES, corpid, formId, formDataUpdateGetDTO.getSaasMark(), formDataUpdateGetDTO.getBusinessType(), "0");
            if (StringUtil.isNotEmpty(value)) {
                formDataUpdateGetVO.setAssignmentRules(Integer.valueOf(value));
            }
            // TODO 需要增加返回权限
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataUpdateGetVO;
    }

    /**
     * 校验数据编辑权限
     *
     * @param formDataUpdateGetDTO
     * @param explainList
     * @param paasFormDataEntityExt
     * @throws XbbException
     */
    private void validateDataEditPermission(FormDataUpdateGetDTO formDataUpdateGetDTO, List<FieldAttrEntity> explainList, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException{
        if(formDataUpdateGetDTO.getIsCopy()){
            //复制不校验编辑权限
            return;
        }
        FormDataDetailDTO formDataDetailDTO = new FormDataDetailDTO();
        BeanUtil.copyProperties(formDataUpdateGetDTO, formDataDetailDTO);
        formDataDetailDTO.setDataCreatorId(paasFormDataEntityExt.getCreatorId());
        VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO(formDataDetailDTO.getLoginUser(), paasFormDataEntityExt);
        boolean hasDataPermission = commonPermissionHelp.checkEditPermission(formDataDetailDTO, verifyUpdatePermissionDTO, ExplainUtil.getExplainMapByList(explainList));
        if (!hasDataPermission){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100050, SystemErrorCodeEnum.API_ERROR_100050.getMsg(), I18nMessageUtil.getMessage(CommonConstant.EDIT));
        }
    }

    /**
     * 通过外链分享页面跳转到编辑页的字段的可编辑处理
     *
     * @param corpid
     * @param explainList
     * @param formId
     * @throws
     * @author long.rao
     * @date 2020-09-03 15:57
     */
    private void handoverOuterLink(String corpid, List<FieldAttrEntity> explainList, Long formId) throws XbbException{
        OuterLinkConfigEntity permissionSetting = outerLinkConfigService.getOuterLinkConfigEntities(corpid, formId, OuterLinkTypeEnum.SHARE.getCode(), OutLinkSettingTypeEnum.PERMISSION_SETTING.getCode());

        Map<String, OutLinkFieldAttrEntity> permissionExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.nonNull(permissionSetting)) {
            List<OutLinkFieldAttrEntity> fieldList = JSONArray.parseArray(permissionSetting.getExplains(), OutLinkFieldAttrEntity.class);
            permissionExplainMap = BeanUtil.convertListToMap(fieldList, "attr");
        }

        for (FieldAttrEntity fieldAttrEntity : explainList) {
            Integer fieldType = fieldAttrEntity.getFieldType();
            OutLinkFieldAttrEntity permissionEntity = permissionExplainMap.get(fieldAttrEntity.getAttr());
            if (ExplainUtil.isSubForm(fieldType)) {
                List<? extends FieldAttrEntity> items = fieldAttrEntity.getSubForm().getItems();
                Map<String, ? extends OutLinkFieldAttrEntity> subPermissionMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                if (Objects.nonNull(permissionEntity) && Objects.nonNull(permissionEntity.getSubForm())) {
                    List<? extends OutLinkFieldAttrEntity> itemsList = permissionEntity.getSubForm().getItems();
                    if (CollectionsUtil.isNotEmpty(itemsList)) {
                        subPermissionMap = BeanUtil.convertListToMap(itemsList, "attr");
                    }
                }
                for (FieldAttrEntity subField : items) {
                    OutLinkFieldAttrEntity subPermissionEntity = subPermissionMap.get(subField.getAttr());
                    if (Objects.nonNull(subPermissionEntity)) {
                        Integer editable = subPermissionEntity.getEditable();
                        if (Objects.equals(editable, BasicConstant.ONE)) {
                            subField.setEditable(BasicConstant.ONE);
                        } else {
                            subField.setEditable(BasicConstant.ZERO);
                        }
                    } else {
                        subField.setEditable(BasicConstant.ZERO);
                    }
                    subField.setEditableAdvanceEnable(BasicConstant.ZERO);

                }
            } else {
                if (Objects.nonNull(permissionEntity)) {
                    Integer editable = permissionEntity.getEditable();
                    if (Objects.equals(editable, BasicConstant.ONE)) {
                        fieldAttrEntity.setEditable(BasicConstant.ONE);
                    } else {
                        fieldAttrEntity.setEditable(BasicConstant.ZERO);
                    }
                } else {
                    fieldAttrEntity.setEditable(BasicConstant.ZERO);
                }
                fieldAttrEntity.setEditableAdvanceEnable(BasicConstant.ZERO);

            }
        }
    }

    @Override
    public ButtonGetVO buttonGet(ButtonGetDTO buttonGetDTO) throws XbbException {
        //TODO 待优化
        ButtonGetVO buttonGetVO = new ButtonGetVO();
        try {
            VerifyUpdatePermissionDTO verifyUpdatePermissionDTO = new VerifyUpdatePermissionDTO();
            BeanUtil.copyProperties(buttonGetDTO, verifyUpdatePermissionDTO);
            verifyUpdatePermissionDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
            ProPermissionHelp.verifyEditPermission(verifyUpdatePermissionDTO);
            //先获取data数据
            String corpid = buttonGetDTO.getCorpid();
            List<Long> dataIdIn = buttonGetDTO.getDataIdIn();
            Integer businessType = buttonGetDTO.getBusinessType();
            PaasFormDataEntityExt formData;
            //确认是否为创建回款单、付款单、其他收入单、其他支出单
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
            boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
            boolean redReceivablesFlag = Objects.equals(businessType, XbbRefTypeEnum.RED_RECEIVABLES.getCode());
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(buttonGetDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(buttonGetVO.getExplainList());
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            List<PaasFormDataEntityExt> dataList = new ArrayList<>();
            // ---- 获取用户和部门容器end
            PaasFormEntityExt paasFormEntityExt = null;
            PaasFormExplainEntity paasFormExplainEntity = null;
            List<FieldAttrEntity> explainList;
            for (Long formDataId : dataIdIn) {
                //需要过滤del不为0的情况
                formData = saasUpdateHelp.getFormData(formDataId, corpid, businessType);
                if (formData == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                if (!Objects.equals(DelEnum.NORMAL.getDel(), formData.getDel())) {
                    continue;
                }
                //只查询一次form表
                if (paasFormEntityExt == null) {
                    paasFormEntityExt = paasFormModel.getByKey(formData.getFormId(), corpid);
                    if (paasFormEntityExt == null) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
                    }
                }
               /* if (FlowStatusEnum.inApproval(formData.getFlowStatus())) {
                    throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200020);
                }*/
                saasAddHelp.handleFormEntity(paasFormEntityExt, SaasMarkEnum.SAAS.getCode(), buttonGetDTO.getBusinessType());
                buttonGetVO.setPaasFormEntity(paasFormEntityExt);
                //只查询一次form_explain表
                if (paasFormExplainEntity == null) {
                    paasFormExplainEntity = paasFormExplainModel.getByFormId(formData.getFormId(), corpid);
                    if (paasFormExplainEntity == null) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                    }
                }
                explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                JSONObject data = formData.getData();
                if (sheetFlag) {
                    //如果是回/付款单、其他收入/支出单，则根据数据data内的回/付款单/其他收入/支出单类型重置sheetTypeEnum（前端传过来的businessType可能没有详细区分哪种类型回/付款单/其他收入/支出单）
                    //新建页和编辑页传参unableEdit不一样
                    fundHelp.handlePaymentSheet(true, sheetTypeEnum, explainList, corpid, paasFormEntityExt.getDistributorMark());
                } else if (redReceivablesFlag) {
                    fundHelp.handleReceivables(explainList);
                    //处理编号、关联原始应收、来源单据、初始化金额等
                    handleRedReceivables4Refund(corpid, formData, formDataId, data);
                }
                // 获取字段解释信息，并且过滤不可见字段
                HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
                BeanUtil.copyProperties(buttonGetDTO, handlerExplainDTO, false);
                handlerExplainDTO.setExplainList(explainList);
                handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);

                // 获取协同人和负责人
                //这边需要兼容一下，红冲回款单按照回款单处理；红冲付款单类型按照付款单处理；红冲应收款单按照应收款处理
                Integer middleBusinessType = businessType;
                if (Objects.equals(XbbRefTypeEnum.RED_PAYMENT_SHEET.getCode(), businessType)) {
                    middleBusinessType = XbbRefTypeEnum.PAYMENT_SHEET.getCode();
                }else if (Objects.equals(XbbRefTypeEnum.RED_WRITE_OFF_PAY.getCode(), businessType)) {
                    middleBusinessType = XbbRefTypeEnum.PAY_SHEET.getCode();
                }else if (Objects.equals(XbbRefTypeEnum.RED_RECEIVABLES.getCode(), businessType)) {
                    middleBusinessType = XbbRefTypeEnum.PAYMENT.getCode();
                }
                paasFormHelp.getOwnerIdAndCoUserId(handlerExplainDTO, SaasMarkEnum.SAAS.getCode(), middleBusinessType, null, formData, userMap);
                List<String> ownerIds = handlerExplainDTO.getOwnerId();
                List<String> coUserIds = handlerExplainDTO.getCoUserId();
                List<ReturnUserAndDepartmentPojo> ownerIdPojoList = new ArrayList<>();
                List<ReturnUserAndDepartmentPojo> coUserIdPojoList = new ArrayList<>();
                if (!Objects.equals(XbbRefTypeEnum.PRODUCT.getCode(), businessType)) {
                    ownerIds.forEach(owner -> {
                        UserEntity userEntity = userMap.get(owner);
                        if (Objects.nonNull(userEntity)) {
                            ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                            BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
                            returnUserAndDepartmentPojo.setId(userEntity.getUserId());
                            ownerIdPojoList.add(returnUserAndDepartmentPojo);
                        }
                    });
                    coUserIds.forEach(coUser -> {
                        UserEntity userEntity = userMap.get(coUser);
                        if (Objects.nonNull(userEntity)) {
                            ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
                            BeanUtil.copyProperties(userEntity, returnUserAndDepartmentPojo);
                            returnUserAndDepartmentPojo.setId(userEntity.getUserId());
                            coUserIdPojoList.add(returnUserAndDepartmentPojo);
                        }
                    });
                }
                HandlerExplainVO handlerExplainVO = formDataFormExplainHandleName.handleExplain(handlerExplainDTO);
                if (handlerExplainVO == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
                }
                boolean formCopy = Objects.nonNull(buttonGetDTO.getSaasSpecialParamPojo()) && Objects.equals(buttonGetDTO.getSaasSpecialParamPojo().getFromCopy(), BasicConstant.ONE);
                proDetailHandlerHelp.handelSaasSpecialUpdate(handlerExplainVO.getHeadList(), buttonGetDTO.getBusinessType(), formData, formCopy, buttonGetDTO.getDistributorMark());
                List<FieldAttrEntity> headList = handlerExplainVO.getHeadList();
                buttonGetVO.setExplainList(headList);


                Map<String, FieldAttrEntity> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (FieldAttrEntity fieldAttrEntity : buttonGetVO.getExplainList()) {
                    // 存放字段容器
                    explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
                }
                SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
                BeanUtil.copyProperties(buttonGetDTO, saasAnalysisDataDTO);
                // saas特殊格式转换
                saasAnalysisDataDTO.setExplainMap(explainMap);
                saasUpdateHelp.formatData(saasAnalysisDataDTO, data);

                // 编辑时saas字段显示特殊逻辑
                FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
                BeanUtil.copyProperties(buttonGetDTO, formatExplainDTO);
                formatExplainDTO.setExplainList(explainList);
                formatExplainDTO.setDataEntity(formData);
                formatExplainDTO.setResult(data);
                SaasSpecialParamPojo saasSpecialParamPojo = new SaasSpecialParamPojo();
                if (Objects.nonNull(buttonGetDTO.getSaasSpecialParamPojo())) {
                    //从红冲页过来formRed 会置成1
                    saasSpecialParamPojo = buttonGetDTO.getSaasSpecialParamPojo();
                }
                formatExplainDTO.setSaasSpecialParamPojo(saasSpecialParamPojo);
                formatExplainDTO.setFormId(paasFormExplainEntity.getFormId());
                formatExplainDTO.setAppId(paasFormExplainEntity.getAppId());
                formatExplainDTO.setMenuId(paasFormExplainEntity.getMenuId());
                formExplainHelp.formatExplain(formatExplainDTO, null);

                data.put(FieldTypeEnum.OWNERID.getAlias(), ownerIdPojoList);
                data.put(FieldTypeEnum.COUSERID.getAlias(), coUserIdPojoList);
                data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), formData.getDepartmentId());
                if (!redReceivablesFlag) {
                    //退货退款的红冲应收编号已经在方法handleRedReceivables4Refund内处理
                    data.put(FieldTypeEnum.SERIALNO.getAlias(), formData.getSerialNo());
                }
                // 解析数据信息
                ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                BeanUtil.copyProperties(buttonGetDTO, parseSingleRowDataDTO);
                parseSingleRowDataDTO.setDataJsonObject(data);
                parseSingleRowDataDTO.setExplainMap(explainMap);
                parseSingleRowDataDTO.setUserMap(userMap);
                parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                ParseSingleRowDataVO parseSingleRowDataVO = formDataUpdateGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
                if (parseSingleRowDataVO == null) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
                JSONObject result = parseSingleRowDataVO.getResult();
                // 获取关联数据的信息
                if (linkResultDataVO != null && !linkResultDataVO.getLinkData().isEmpty() && !linkResultDataVO.getLinkDataSet().isEmpty()) {
                    FormDataUpdateGetDTO formDataGetDTO = new FormDataUpdateGetDTO();
                    BeanUtil.copyProperties(buttonGetDTO, formDataGetDTO);
                    linkResultDataVO.setData(result);
                    linkResultDataVO.setExplainMap(explainMap);
                    linkResultDataVO.setUserMap(userMap);
                    linkResultDataVO.setDepartmentMap(departmentMap);
                    linkResultDataVO.setExplainList(explainList);
                    result = formDataLinkDataUpdateGetService.formDataLinkDataGet(formDataGetDTO, linkResultDataVO);
                }
                //组装发票金额明细 规避掉解析
                if (Objects.equals(businessType, XbbRefTypeEnum.INVOICE.getCode())) {
                    invoiceCommonHelper.getUpdateDataBySalesInvoice(null,buttonGetDTO,saasSpecialParamPojo,formData,result,explainList);
//                    fundHelp.setInvoiceNotEditToExplain(buttonGetVO.getExplainList(),formRed,isRed,businessType);
                } else if (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE_INVOICE.getCode())) {
                    invoiceCommonHelper.getUpdateDataByPurchaseInvoice(null,buttonGetDTO,saasSpecialParamPojo,formData,result,explainList);
//                    fundHelp.setInvoiceNotEditToExplain(buttonGetVO.getExplainList(),purchaseInvoiceAmountDetailGetDTO.getFormRed(),purchaseInvoiceAmountDetailGetDTO.getIsRed(),businessType);
                } else if (sheetFlag) {
                    if (Objects.equals(sheetTypeEnum.getXbbRefTypeEnum(), XbbRefTypeEnum.PAY_SHEET)) {
                        paySheetAmountDetailHandleInReturnedPurchase(parseSingleRowDataDTO, result, formDataId, corpid);
                    } else if (Objects.equals(sheetTypeEnum.getXbbRefTypeEnum(), XbbRefTypeEnum.PAYMENT_SHEET)) {
                        paymentSheetAmountDetailHandleInRefund(parseSingleRowDataDTO, result, formDataId, corpid);
                    }
                    paymentSheetAmountTransform(sheetTypeEnum.getXbbRefTypeEnum(), result);
                }
                formData.setData(result);
                dataList.add(formData);
            }
            buttonGetVO.setDataList(dataList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return buttonGetVO;
    }



    @Override
    public FormCountGetVO count(FormCountGetDTO formCountGetDTO) throws XbbException {
        FormCountGetVO formCountGetVO = new FormCountGetVO();
        try {
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            //解析查询条件
            boolQueryBuilder.filter(termQuery("corpid.keyword", formCountGetDTO.getCorpid()));
            boolQueryBuilder.filter(termQuery("menuId", formCountGetDTO.getMenuId()));
            boolQueryBuilder.filter(termQuery("appId", formCountGetDTO.getAppId()));
            boolQueryBuilder.filter(termQuery("del", 0));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_FORM_DATA.getType()));
            sourceBuilder.query(boolQueryBuilder);
            SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_FORM_DATA.getIndex());
            searchRequest.source(sourceBuilder);
            long count = paasFormDataEsModel.count(searchRequest);
            formCountGetVO.setDataCount(count);
        } catch (Exception e) {
            LOG.error("paasFormData.count数据库查询总记录数出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formCountGetVO;
    }

    @Override
    public SearchDataInConditionVO searchDataInProcessCondition(SearchDataInConditionDTO searchDataInConditionDTO) throws XbbException {
        SearchDataInConditionVO searchDataInConditionVO = new SearchDataInConditionVO();
        try {
            if(Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT_PERFORMANCE.getCode()) || Objects.equals(searchDataInConditionDTO.getBusinessType(),XbbRefTypeEnum.CONTRACT_PRODUCT.getCode())){
                return searchDataInConditionVO;
            }
            dealSubForm4SharePermission(searchDataInConditionDTO);
            //多表用originalAttr取代attr去查下拉选项。
            boolean subAttr = false;
            if (Objects.nonNull(searchDataInConditionDTO.getOriginalAttr())) {
                searchDataInConditionDTO.setAttr(searchDataInConditionDTO.getOriginalAttr());
                if (searchDataInConditionDTO.getAttr().contains(StringConstant.POINT)) {
                    subAttr = true;
                }
            }
            if (!subAttr && searchDataInConditionDTO.getAttr().contains(StringConstant.POINT) ) {
                subAttr = true;
            }
            ConditionExplainPojo conditionExplainPojo = getFieldAttr(searchDataInConditionDTO);
            FieldAttrEntity fieldAttrEntity = conditionExplainPojo.getParentFieldAttr();
            if (Objects.nonNull(conditionExplainPojo.getSubFieldAttr())) {
                fieldAttrEntity = conditionExplainPojo.getSubFieldAttr();
            }
            //fieldType实时从解释里面去拿
            FieldTypeEnum fieldTypeEnum = null;
            if (Objects.nonNull(fieldAttrEntity)) {
                fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldAttrEntity.getFieldType());
            }
            if (Objects.isNull(fieldTypeEnum)) {
                return searchDataInConditionVO;
            }
            switch (fieldTypeEnum) {
                case COMBO:
                case RADIO_GROUP:
                case COMBO_CHECK:
                case CHECKBOX_GROUP:
                    ComboTypeEnum comboTypeEnum = ComboTypeEnum.getComboTypeEnum(fieldAttrEntity.getComboType());
                    switch (comboTypeEnum) {
                        case CUSTOM:
                            List<ItemDataPoJo> items = getCustomList(searchDataInConditionDTO, fieldAttrEntity, subAttr, conditionExplainPojo);
                            List<String> fromList = Arrays.asList(SearchDataFromEnum.PROCESS.getFrom(), SearchDataFromEnum.SHARE_PERMISSION.getFrom());
                            if (fromList.contains(searchDataInConditionDTO.getFrom())) {
                                if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.OTHER_INSTOCK.getCode()) && Objects.equals(fieldAttrEntity.getAttr(), InstockEnum.TYPE.getAttr())) {
                                    items.removeIf(itemDataPoJo -> Objects.equals(itemDataPoJo.getValue(), Objects.toString(InstockTypeEnum.ASSEMBLE_INSTOCK.getCode())));
                                }
                                if (Objects.equals(searchDataInConditionDTO.getBusinessType(), XbbRefTypeEnum.OTHER_OUTSTOCK.getCode()) && Objects.equals(fieldAttrEntity.getAttr(), OutstockEnum.TYPE.getAttr())) {
                                    items.removeIf(itemDataPoJo -> Objects.equals(itemDataPoJo.getValue(), Objects.toString(OutstockTypeEnum.ASSEMBLE_OUTSTOCK.getCode())));
                                }
                            }
                            searchDataInConditionVO.setItems(items);
                            break;
                        case LINKFORM:
                            //查询限制
                            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
                            searchDataInConditionDTO.setLinkForm(fieldAttrEntity.getLinkForm());
                            searchDataInConditionVO = distinctDataService.listOfLinkForm(searchDataInConditionDTO);
                            break;
                        case DATARELY:
                            //查询限制
                            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
                            searchDataInConditionDTO.setRely(fieldAttrEntity.getDefaultAttr().getRely());
                            searchDataInConditionVO = distinctDataService.listOfRely(searchDataInConditionDTO);
                            break;
                        case BUSINESS:
                            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
                            searchDataInConditionVO = distinctDataService.listOfText(conditionExplainPojo, fieldAttrEntity, searchDataInConditionDTO, fieldTypeEnum);
                            break;
                        default:
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.DATA_NOT_STANDARD);
                    }
                    break;
                case STAGE_THRUSTER:
                    searchDataInConditionVO = distinctDataService.listofStageInfo(searchDataInConditionDTO, fieldAttrEntity);
                    break;
                default:
                    searchDataInConditionVO = getConditionDataList(conditionExplainPojo, fieldAttrEntity, searchDataInConditionDTO);
                    break;
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData.searchDataInProcessCondition流程流转条件根据字段检索数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return searchDataInConditionVO;
    }

    /**
     * for 共享权限，子表单attr前端分开了，要合回去
     * @param searchDataInConditionDTO
     */
    private void dealSubForm4SharePermission(SearchDataInConditionDTO searchDataInConditionDTO) {
        if (!Objects.equals(searchDataInConditionDTO.getFrom(), SearchDataFromEnum.SHARE_PERMISSION.getFrom())
                || StringUtils.isEmpty(searchDataInConditionDTO.getSubAttr())) {
            return;
        }
        StringBuilder attr = new StringBuilder(searchDataInConditionDTO.getAttr());
        attr.append(".").append(searchDataInConditionDTO.getSubAttr());
        searchDataInConditionDTO.setAttr(attr.toString());
    }

    @Override
    public LinkFormDataVO linkFormData(LinkFormDataDTO linkFormDataDTO) throws XbbException {
        LinkFormDataVO linkFormDataVO = new LinkFormDataVO();
        try {
            LinkFormPoJo linkFormPoJo = linkFormDataDTO.getLinkForm();
            SearchDataInConditionDTO searchDataInConditionDTO = new SearchDataInConditionDTO();
            BeanUtil.copyProperties(linkFormDataDTO, searchDataInConditionDTO);
            searchDataInConditionDTO.setSaasMark(linkFormPoJo.getSourceSaasMark());
            searchDataInConditionDTO.setBusinessType(linkFormPoJo.getSourceBusinessType());
            searchDataInConditionDTO.setFormId(linkFormPoJo.getSourceFormId());
            saasListHelp.packageSearchDataCondition(searchDataInConditionDTO);
            SearchDataInConditionVO searchDataInConditionVO = distinctDataService.listOfLinkForm(searchDataInConditionDTO);
            List<ItemDataPoJo> items = new ArrayList<>();
            if ( searchDataInConditionVO != null ) {
                items = searchDataInConditionVO.getItems();
            }
            linkFormDataVO.setItems(items);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData.linkFormData下拉框联动其他表单出错出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return linkFormDataVO;
    }

    @Override
    public LinkRelyDataVO linkRelyData(LinkRelyDataDTO linkRelyDataDTO) throws XbbException {
        LinkRelyDataVO linkRelyDataVO = new LinkRelyDataVO();
        try {
            SearchDataInConditionDTO searchDataInConditionDTO = new SearchDataInConditionDTO();
            BeanUtil.copyProperties(linkRelyDataDTO, searchDataInConditionDTO);

            SearchDataInConditionVO searchDataInConditionVO = distinctDataService.linkRelyList(searchDataInConditionDTO);
            if ( searchDataInConditionVO != null ) {
                linkRelyDataVO.setItems(searchDataInConditionVO.getItems());
                linkRelyDataVO.setDataList(searchDataInConditionVO.getDataList());
            }

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData.linkRelyData下拉框数据联动出错出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return linkRelyDataVO;
    }

    @Override
    public LinkRelyDataWorkOrderPhoneVO linkWorkOrderPhone(LinkWorkOrderPhoneDTO linkWorkOrderPhoneDTO) throws XbbException {
        LinkRelyDataWorkOrderPhoneVO linkRelyDataWorkOrderPhoneVO = new LinkRelyDataWorkOrderPhoneVO();
        Integer businessType = linkWorkOrderPhoneDTO.getBusinessType();
        String corpid = linkWorkOrderPhoneDTO.getCorpid();
        Long dataId = linkWorkOrderPhoneDTO.getDataId();
        try {
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                CustomerEntityExt customerEntity = customerModel.getByKey(dataId, corpid);
                if(Objects.isNull(customerEntity)){
                    LOG.error("paasFormData.linkWorkOrderPhone获取客户出错");
                    throw new XbbException(CustomerErrorCodeEnum.API_ERROR_201001, CustomerErrorCodeEnum.API_ERROR_201001.getMsg());
                }
                Long formId = customerEntity.getFormId();
                PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId,corpid);
                Map<String,FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), CustomerManagementEnum.PHONE.getAttr());
                FieldAttrEntity phoneFieldAttrEntity = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                if (Objects.isNull(phoneFieldAttrEntity.getSubForm()) || Objects.isNull(phoneFieldAttrEntity.getSubForm().getItems())){
                    return null;
                }
                List<FieldAttrEntity> subExplainList = JSONArray.parseArray(JSON.toJSONString(phoneFieldAttrEntity.getSubForm().getItems()), FieldAttrEntity.class);
                Map<String,FieldAttrEntity> map = ExplainUtil.getExplainMapByList(subExplainList,"text_1");
                FieldAttrEntity fieldAttrEntity = map.get("text_1");
                JSONObject data = customerEntity.getData();
                JSONArray phone = data.getJSONArray(CustomerManagementEnum.PHONE.getAttr());
                if (Objects.nonNull(phone)){
                    for (int i = 0; i < phone.size(); i++) {
                        JSONObject jsonObject = phone.getJSONObject(i);
                        String code = jsonObject.getString("text_1");
                        String name = PhoneExtEnum.getNameByCode(code);
                        JSONObject newJSONObject = new JSONObject();
                        newJSONObject.put("text",name);
                        newJSONObject.put("value",code);
                        jsonObject.put("text_1",newJSONObject);
                    }
                }
                if (Objects.nonNull(phone)){
                    for (int i = 0; i < phone.size(); i++) {
                        JSONObject jsonObject = phone.getJSONObject(i);
                        JSONObject newJSONObject = new JSONObject();
                        formDataAnalysisHelp.analysisCombo(jsonObject,newJSONObject,fieldAttrEntity, linkWorkOrderPhoneDTO.getCorpid());
                        JSONObject json = newJSONObject.getJSONObject("text_1");
//                        String value = jsonObject.getString("text_1");
//                        newJSONObject.clear();
//                        newJSONObject.put("text",text);
//                        newJSONObject.put("value",value);
                        List<String> codes = Arrays.asList("1","2","3","4","5","6");
                        if(!codes.contains(json.getString("value"))){
                            json.put("text",json.getString("value"));
                        }
                        jsonObject.put("text_1",json);
                    }
                }
                linkRelyDataWorkOrderPhoneVO.setDataList(phone);
            } else if (Objects.equals(businessType, XbbRefTypeEnum.CONTACT.getCode())) {
                ContactEntityExt contactEntityExt = contactModel.getByKey(dataId,corpid);
                if(Objects.isNull(contactEntityExt)){
                    LOG.error("paasFormData.linkWorkOrderPhone获取客户联系人出错");
                    throw new XbbException(ContactErrorCodeEnum.API_ERROR_204006, ContactErrorCodeEnum.API_ERROR_204006.getMsg());
                }
                Long formId = contactEntityExt.getFormId();
                PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId,corpid);
                Map<String,FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainEntity.getExplains(), ContactEnum.PHONE.getAttr());
                FieldAttrEntity phoneFieldAttrEntity = explainMap.get(ContactEnum.PHONE.getAttr());
                if (Objects.isNull(phoneFieldAttrEntity.getSubForm()) || Objects.isNull(phoneFieldAttrEntity.getSubForm().getItems())){
                    return null;
                }
                List<FieldAttrEntity> subExplainList = JSONArray.parseArray(JSON.toJSONString(phoneFieldAttrEntity.getSubForm().getItems()), FieldAttrEntity.class);
                Map<String,FieldAttrEntity> map = ExplainUtil.getExplainMapByList(subExplainList,"text_1");
                FieldAttrEntity fieldAttrEntity = map.get("text_1");

                JSONObject data = contactEntityExt.getData();
                JSONArray phone = data.getJSONArray(ContactEnum.PHONE.getAttr());
                if(Objects.nonNull(phone)){
                    for (int i = 0; i < phone.size(); i++) {
                        JSONObject jsonObject = phone.getJSONObject(i);
                        String code = jsonObject.getString("text_1");
                        String name = PhoneExtEnum.getNameByCode(code);
                        JSONObject newJSONObject = new JSONObject();
                        newJSONObject.put("text",name);
                        newJSONObject.put("value",code);
                        jsonObject.put("text_1",newJSONObject);
                    }
                }
                if(Objects.nonNull(phone)){
                    for (int i = 0; i < phone.size(); i++) {
                        JSONObject jsonObject = phone.getJSONObject(i);
                        JSONObject newJSONObject = new JSONObject();
                        formDataAnalysisHelp.analysisCombo(jsonObject,newJSONObject,fieldAttrEntity, linkWorkOrderPhoneDTO.getCorpid());
                        JSONObject json = newJSONObject.getJSONObject("text_1");
//                        String value = jsonObject.getString("text_1");
//                        newJSONObject.clear();
//                        newJSONObject.put("text",text);
//                        newJSONObject.put("value",value);
                        List<String> codes = Arrays.asList("1","2","3","4","5","6");
                        if(!codes.contains(json.getString("value"))){
                            json.put("text",json.getString("value"));
                        }
                        jsonObject.put("text_1",json);
                    }
                }
                linkRelyDataWorkOrderPhoneVO.setDataList(phone);
            }
        } catch (Exception e) {
            LOG.error("paasFormData.linkWorkOrderPhone出错", e);
            throw e;
        }
        return linkRelyDataWorkOrderPhoneVO;
    }

    @Override
    public FormDataFastUpdateVO fastUpdate(FormDataFastUpdateDTO formDataFastUpdateDTO) throws XbbException {
        FormDataFastUpdateVO formDataFastUpdateVO = new FormDataFastUpdateVO();
        try {
            String corpid = formDataFastUpdateDTO.getCorpid();
            PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataFastUpdateDTO.getFormId(), corpid);
            if ( Objects.isNull(paasFormEntityExt) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            String businessName = paasFormEntityExt.getBusinessName();
            Long key = formDataFastUpdateDTO.getDataId();
            PaasFormDataEntity paasFormDataEntity = paasFormDataModel.getByKey(key, corpid);
            if ( paasFormDataEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            Map<String, Object> param = BeanUtil.convertBean2Map(formDataFastUpdateDTO, true);
            param.put("key", "$." + formDataFastUpdateDTO.getAttr());
            // TODO 子表单不支持快速编辑
            paasFormDataModel.fastUpdate(param, key, corpid);
            formDataFastUpdateVO.setFormDataId(formDataFastUpdateDTO.getDataId());
            formDataFastUpdateVO.setMenuId(formDataFastUpdateDTO.getMenuId());
            formDataFastUpdateVO.setAppId(formDataFastUpdateDTO.getAppId());
            String userId = formDataFastUpdateDTO.getUserId();
            String name = formDataFastUpdateDTO.getLoginUserName();
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_UPDATE_FORM_DATA), name, formDataFastUpdateDTO.getValue(), businessName, formDataFastUpdateDTO.getAttr());
            mongoLogHelp.buildLog(corpid, userId, name, OperateModuleTypeEnum.PAAS_FORM_DATA, OperateTypeEnum.EDIT, formDataFastUpdateDTO.getAppId().toString(), "", memo, formDataFastUpdateDTO.getHttpHeader());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData.fastUpdate快速编辑出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataFastUpdateVO;
    }

    @Override
    public FormDataRestoreVO restore(FormDataRestoreDTO formDataRestoreDTO) throws XbbException {
        FormDataRestoreVO formDataRestoreVO = new FormDataRestoreVO();
        try {
            String corpid = formDataRestoreDTO.getCorpid();
            List<Long> dataIdList = formDataRestoreDTO.getDataIdList();
            List<PaasFormDataEntity> dataList = paasFormDataModel.findEntitysByIds(dataIdList, corpid, formDataRestoreDTO.getDel());
            if ( dataList == null || dataList.size() != dataIdList.size() ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            paasFormDataModel.restoreBatch(dataIdList, corpid, DelEnum.NORMAL.getDel());
            //富文本还原单独处理
            richTextService.operateBatch(new FormRichTextBatchDTO(corpid, formDataRestoreDTO.getFormId(), formDataRestoreDTO.getBusinessType(),
                    formDataRestoreDTO.getSaasMark(), dataIdList, DelEnum.DELETE.getDel(), DelEnum.NORMAL.getDel()));
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData.restore数据还原出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataRestoreVO;
    }

    @Override
    public CheckRepeatVO repeat(FormDataRepeatDTO formDataRepeatDTO) throws XbbException {
        return repeatHelp.repeat(formDataRepeatDTO);
    }

    @Override
    public FormDataRepeatVO repeat(FormDataRepeatDTO formDataRepeatDTO, Map<String, Object> repeatValueMap) throws XbbException {
        FormDataRepeatVO formDataRepeatVO = new FormDataRepeatVO();
        if ( repeatValueMap == null || repeatValueMap.isEmpty() ) {
            return formDataRepeatVO;
        }
        try {
            String corpid = formDataRepeatDTO.getCorpid();
            Integer businessType = formDataRepeatDTO.getBusinessType();
            boolean repeatFlag = Objects.equals(businessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.CONTACT.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
            if (repeatFlag) {
                //查重能力提升改造
                formDataRepeatVO = repeatHelp.importRepeat(formDataRepeatDTO,repeatValueMap);
            } else {
                SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
                BoolQueryBuilder boolQueryBuilder = boolQuery();
                EsUtil.getTermQuery(boolQueryBuilder, formDataRepeatDTO, true);
                Set<Map.Entry<String, Object>> entrySet = repeatValueMap.entrySet();
                Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Object> entry = iterator.next();
                    String attr = entry.getKey();
                    Object value = entry.getValue();
                    if (Objects.equals(attr, FieldTypeEnum.SERIALNO.getAlias())) {
                        // 编号
                        String serialNoAttr = FieldTypeEnum.SERIALNO.getAlias() + StringConstant.POINT + StringConstant.KEY_WORD;
                        boolQueryBuilder.should(termQuery(serialNoAttr, value));
                    } else {
                        if (attr.contains(StringConstant.COMMA)) {
                            attr = "data." + attr.split(StringConstant.COMMA)[0] + "." + attr.split(StringConstant.COMMA)[1] + ".keyword";
                        } else {
                            attr = "data." + attr + ".keyword";
                        }
                        QueryBuilder queryBuilder = QueryBuilders.termQuery(attr, value);
                        boolQueryBuilder.should(queryBuilder);
                    }
                }
                boolQueryBuilder.minimumShouldMatch(EsNormalConstant.MINI_MUM_SHOULD_MATCH);
                // 回收站也要查重
                if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                    boolQueryBuilder.filter(termsQuery(ParameterConstant.DEL, Arrays.asList(DelEnum.NORMAL.getDel(), DelEnum.DELETE.getDel())));
                } else {
                    boolQueryBuilder.filter(termQuery(ParameterConstant.DEL, DelEnum.NORMAL.getDel()));
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                    boolQueryBuilder.filter(termQuery("data." + ProductEnum.PARENT_ID.getAttr(), BasicConstant.ZERO));
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode())) {
                    boolQueryBuilder.filter(termQuery("data." + DistributorAccountEnum.ACCOUNT_STATUS.getAttr(), BasicConstant.ONE));
                }
                Integer saasMark = formDataRepeatDTO.getSaasMark();
                IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, saasMark);

                if (commonHelp.isOpenWorkFlow(corpid)) {
                    // 如果开启了工作流，审批中数据会进入主表，查重的时候可以直接从主表查到
                    boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType(), FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
                } else {
                    boolQueryBuilder.filter(termsQuery(FieldTypeEnum.FLOW_STATUS.getAlias(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
                }

                boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, indexTypeEnum.getType()));
                SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
                //TODO 没找到page相关的代码，默认查询20条 2019年6月27日11:08:03
                PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 10);
                sourceBuilder.query(boolQueryBuilder);
                searchRequest.source(sourceBuilder);
                formDataRepeatVO = paasFormDataEsModel.repeat(pageRequest, searchRequest);
            }
        } catch (Exception e) {
            LOG.error("paasFormData.repeat查询数据重复出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataRepeatVO;
    }


    @Override
    public FormDataRepeatBatchVO repeatBatch(FormDataRepeatBatchDTO formDataRepeatBatchDTO) throws XbbException {
        FormDataRepeatBatchVO formDataRepeatBatchVO;
        try {
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            EsUtil.getTermQuery(boolQueryBuilder, formDataRepeatBatchDTO, true);
            // 编号
            boolQueryBuilder.filter(termsQuery(FieldTypeEnum.SERIALNO.getAlias(), formDataRepeatBatchDTO.getSerialNoList()));
            Integer saasMark = formDataRepeatBatchDTO.getSaasMark();
            Integer businessType = formDataRepeatBatchDTO.getBusinessType();
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(formDataRepeatBatchDTO.getCorpid(), saasMark, businessType);
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,indexTypeEnum.getType()));
            SearchRequest searchRequest = new SearchRequest(indexTypeEnum.getIndex());
            //TODO 没找到page相关的代码，默认查询20条 2019年6月27日11:08:03
            PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 20);
            sourceBuilder.query(boolQueryBuilder);
            searchRequest.source(sourceBuilder);
            formDataRepeatBatchVO = paasFormDataEsModel.repeatBatch(pageRequest, searchRequest);
        } catch (Exception e) {
            LOG.error("paasFormData.repeatBatch查询数据重复出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataRepeatBatchVO;
    }

    @Override
    public ProcessDataAddFormDataVO processDataAddFormData(ProcessDataAddFormDataDTO processDataAddFormDataDTO) throws XbbException {
        // 更新流程状态和流程负责人
        return processDataSynchronizedFormService.processDataAddFormData(processDataAddFormDataDTO);
    }



    @Override
    public ProcessDataUpdateFormDataVO processDataUpdateFormData(ProcessDataUpdateFormDataDTO processDataUpdateFormDataDTO) throws XbbException {
        return processDataSynchronizedFormService.processDataUpdateFormData(processDataUpdateFormDataDTO);
//        // 更新流程状态和流程负责人
//        ProcessDataUpdateFormDataVO processDataUpdateFormDataVO = new ProcessDataUpdateFormDataVO();
//        try {
//            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
//            if ( processDataUpdateFormDataDTO.getOwnerId() == null ) {
//                processDataUpdateFormDataDTO.setOwnerId("");
//            }
//            JSONObject data = JsonHelperUtil.parseObject(processDataUpdateFormDataDTO.getData());
//            if (processDataUpdateFormDataDTO.getFlowStatus().equals(FlowStatusEnum.PASS.getType())) {
//                // 流程通过时，将流程数据同步进表单数据
//                paasFormDataEntity.setData(data);
//            }
//            paasFormDataEntity.setId(processDataUpdateFormDataDTO.getFormDataId());
//            paasFormDataEntity.setCorpid(processDataUpdateFormDataDTO.getCorpid());
//            paasFormDataEntity.setFlowStatus(processDataUpdateFormDataDTO.getFlowStatus());
//            paasFormDataEntity.setSerialNo(processDataUpdateFormDataDTO.getSerialNo());
//            paasFormDataEntity.setOwnerId(processDataUpdateFormDataDTO.getOwnerId());
//            paasFormDataEntity.setDepartmentId(processDataUpdateFormDataDTO.getDepartmentId());
//            paasFormDataEntity.setFormId(processDataUpdateFormDataDTO.getFormId());
//            paasFormDataEntity.setCreatorId(processDataUpdateFormDataDTO.getCreatorId());
//            FormDataUpdateDTO formDataUpdateDTO = new FormDataUpdateDTO();
//            BeanUtil.copyProperties(processDataUpdateFormDataDTO, formDataUpdateDTO);
//            formDataUpdateDTO.setIsFromProcess(1);
//            if (!Objects.equals(processDataUpdateFormDataDTO.getSubBusinessType(), XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode()) || !Objects.equals(processDataUpdateFormDataDTO.getSubBusinessType(), XbbRefTypeEnum.CLUE_PUBLIC.getCode())) {
//                formDataUpdateDTO.setOwnerId(Collections.singletonList(new ReturnUserAndDepartmentPojo(processDataUpdateFormDataDTO.getOwnerId())));
//            }
//            formDataUpdateDTO.setDataId(processDataUpdateFormDataDTO.getFormDataId());
//            PaasFormDataEntity oldPaasFormDataEntity = proModelService.getOldPaasFormDataEntity(formDataUpdateDTO);
//            PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
//            if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
//                WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(processDataUpdateFormDataDTO.getFormId(), processDataUpdateFormDataDTO.getCorpid());
//                BeanUtil.copyProperties(workOrderExplainEntityExt, paasFormExplainEntity);
//            }/* else if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAY_SHEET.getCode()) || Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAYMENT_SHEET.getCode()) ) {
//                paasFormExplainEntity = paasFormExplainModel.getByBusinessType(processDataUpdateFormDataDTO.getBusinessType(), processDataUpdateFormDataDTO.getCorpid());
//            } */else {
//                paasFormExplainEntity = paasFormExplainModel.getByFormId(processDataUpdateFormDataDTO.getFormId(), processDataUpdateFormDataDTO.getCorpid());
//            }
//            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
//            WorkOrderFormEntity workOrderFormEntity = new WorkOrderFormEntity();
//            if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
//                workOrderFormEntity = workOrderFormModel.getByKey(processDataUpdateFormDataDTO.getFormId(), processDataUpdateFormDataDTO.getCorpid());
//                if ( workOrderFormEntity == null ) {
//                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
//                }
//                BeanUtil.copyProperties(workOrderFormEntity, paasFormEntityExt);
//                paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
//                paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
//            } else {
//                paasFormEntityExt = paasFormModel.getByKey(processDataUpdateFormDataDTO.getFormId(), processDataUpdateFormDataDTO.getCorpid());
//            }
//            if ( paasFormEntityExt == null ) {
//                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
//            }
//            List<FieldAttrEntity> fieldList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
//            Map<String, FieldAttrEntity> explainMap = new HashMap<>(fieldList.size());
//            fieldList.forEach(item->{explainMap.put(item.getAttr(), item);});
//            formDataUpdateDTO.setExplainMap(explainMap);
//            String formName = paasFormEntityExt.getName();
//            formDataUpdateDTO.setProcessCreatorId(processDataUpdateFormDataDTO.getCreatorId());
//            if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAYMENT_SHEET.getCode()) ) {
//                String paymentSheetType = saasGetHelp.getStringFromFormData(paasFormDataEntity.getData(), PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr());
//                PaymentSheetTypeEnum paymentSheetTypeEnum = PaymentSheetTypeEnum.getByCode(paymentSheetType);
//                formDataUpdateDTO.setBusinessType(paymentSheetTypeEnum.getBusinessType());
//                PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
//                paasProcessDataEntity.setCorpid(processDataUpdateFormDataDTO.getCorpid());
//                paasProcessDataEntity.setSaasMark(1);
//                paasProcessDataEntity.setBusinessType(paymentSheetTypeEnum.getBusinessType());
//                paasProcessDataEntity.setFormDataId(oldPaasFormDataEntity.getId());
//                proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
//            } else if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAY_SHEET.getCode()) ) {
//                String paySheetType = saasGetHelp.getStringFromFormData(paasFormDataEntity.getData(), PaySheetEnum.PAY_SHEET_TYPE.getAttr());
//                PaySheetTypeEnum paySheetTypeEnum = PaySheetTypeEnum.getByCode(paySheetType);
//                formDataUpdateDTO.setBusinessType(paySheetTypeEnum.getBusinessType());
//                PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
//                paasProcessDataEntity.setCorpid(processDataUpdateFormDataDTO.getCorpid());
//                paasProcessDataEntity.setSaasMark(1);
//                paasProcessDataEntity.setBusinessType(paySheetTypeEnum.getBusinessType());
//                paasProcessDataEntity.setFormDataId(oldPaasFormDataEntity.getId());
//                proModelService.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
//            }
//            Integer updateLine = 0;
//            if ( Objects.equals(formDataUpdateDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
//                WorkOrderEntity oldWorkOrderEntity = proModelService.getOldWorkOrderEntity(formDataUpdateDTO);
//                // 不给默认值
//                WorkOrderEntity workOrderEntity = new WorkOrderEntity(null);
//                BeanUtil.copyProperties(paasFormDataEntity, workOrderEntity);
//                FormDataUpdateService abstractFormDataService = formDataUpdateServiceFactory.getFormDataUpdateService(formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getSaasMark());
//                BeforeUpdateVO beforeSaveVO = new BeforeUpdateVO();
//                beforeSaveVO.setWorkOrderEntity(workOrderEntity);
//                beforeSaveVO.setOldWorkOrderEntity(oldWorkOrderEntity);
//                beforeSaveVO.setSaasNeedRedundantAttrPojo(formDataUpdateDTO.getSaasNeedRedundantAttrPoJo());
//                beforeSaveVO.setExplainMap(explainMap);
//                beforeSaveVO.setExplainList(fieldList);
//                beforeSaveVO.setNoApprovalRequired(1);
//                beforeSaveVO.setWorkOrderFormEntity(workOrderFormEntity);
//                UpdateVO saveVO = abstractFormDataService.update(formDataUpdateDTO, beforeSaveVO);
//                abstractFormDataService.afterSave(formDataUpdateDTO, beforeSaveVO, saveVO);
//                updateLine = saveVO.getUpdateLine();
//            } else {
//                OwnerIdAndCoUserIdUtil.setOwnIdAndCoUserId(paasFormDataEntity.getData(), null, formDataUpdateDTO);
//                if (StockConstant.OTHER_STOCK_TYPE_LIST.contains(processDataUpdateFormDataDTO.getBusinessType())) {
//                    Integer stockBusinessType = null;
//                    if (Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_INSTOCK.getCode())) {
//                        Integer type = data.getInteger(InstockEnum.TYPE.getAttr());
//                        InstockTypeEnum instockTypeEnum = InstockTypeEnum.getByCode(type);
//                        stockBusinessType = instockTypeEnum.getStockBusinessType();
//                    } else if (Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())) {
//                        Integer type =data.getInteger(OutstockEnum.TYPE.getAttr());
//                        OutstockTypeEnum outstockTypeEnum = OutstockTypeEnum.getByCode(type);
//                        stockBusinessType = outstockTypeEnum.getStockBusinessType();
//                    }
//                    PaasFormEntityExt realStockFormEntity = paasFormModel.getByBusinessType(stockBusinessType, processDataUpdateFormDataDTO.getCorpid());
//                    if (Objects.isNull(realStockFormEntity)) {
//                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
//                    }
//                    formDataUpdateDTO.setAppId(realStockFormEntity.getAppId());
//                    formDataUpdateDTO.setMenuId(realStockFormEntity.getMenuId());
//                    formDataUpdateDTO.setFormId(realStockFormEntity.getId());
//                    formDataUpdateDTO.setBusinessType(realStockFormEntity.getBusinessType());
//                    formDataUpdateDTO.setSubBusinessType(realStockFormEntity.getBusinessType());
//                    paasFormDataEntity.setAppId(realStockFormEntity.getAppId());
//                    paasFormDataEntity.setMenuId(realStockFormEntity.getMenuId());
//                    paasFormDataEntity.setFormId(realStockFormEntity.getId());
//                    oldPaasFormDataEntity.setAppId(realStockFormEntity.getAppId());
//                    oldPaasFormDataEntity.setMenuId(realStockFormEntity.getMenuId());
//                    oldPaasFormDataEntity.setFormId(realStockFormEntity.getId());
//                    paasFormEntityExt = realStockFormEntity;
//                }
//                AfterSaveVO afterSaveVO;
//                if (Objects.equals(paasFormExplainEntity.getDistributorMark(), 1)) {
//                    afterSaveVO = distributorProModelService.update(formDataUpdateDTO, paasFormDataEntity, oldPaasFormDataEntity, paasFormEntityExt);
//                } else {
//                    FormDataUpdateService abstractFormDataService = formDataUpdateServiceFactory.getFormDataUpdateService(formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getSaasMark());
//                    BeforeUpdateVO beforeSaveVO = new BeforeUpdateVO();
//                    beforeSaveVO.setPaasFormDataEntity(paasFormDataEntity);
//                    beforeSaveVO.setOldPaasFormData(oldPaasFormDataEntity);
//                    beforeSaveVO.setPaasFormEntityExt(paasFormEntityExt);
//                    beforeSaveVO.setSaasNeedRedundantAttrPojo(formDataUpdateDTO.getSaasNeedRedundantAttrPoJo());
//                    beforeSaveVO.setExplainMap(explainMap);
//                    beforeSaveVO.setExplainList(fieldList);
//                    beforeSaveVO.setNoApprovalRequired(1);
//                    UpdateVO saveVO = abstractFormDataService.update(formDataUpdateDTO, beforeSaveVO);
//                    abstractFormDataService.afterSave(formDataUpdateDTO, beforeSaveVO, saveVO);
//                    updateLine = saveVO.getUpdateLine();
//                }
//
//            }
//            // paas的逻辑 paasFormDataModel.processDataUpdateFormData(paasFormDataEntity)
//            processDataUpdateFormDataVO.setFormDataId(processDataUpdateFormDataDTO.getFormDataId());
//
//        } catch (XbbException e) {
//            throw e;
//        } catch (Exception e) {
//            LOG.error("paasFormData.updateFlowStatus数据库更新流程状态和流程负责人操作出错", e);
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
//        }
//        return processDataUpdateFormDataVO;
    }

    @Override
    public DeleteFormDataByBusinessRuleVO deleteFormDataByBusinessRule(DeleteFormDataByBusinessRuleDTO deleteFormDataByBusinessRuleDTO) throws XbbException {
        DeleteFormDataByBusinessRuleVO deleteFormDataByBusinessRuleVO = new DeleteFormDataByBusinessRuleVO();
        try {
            String corpid = deleteFormDataByBusinessRuleDTO.getCorpid();
            Integer del = DelEnum.DELETE.getDel();
            List<Long> ids = new ArrayList<>();
            deleteFormDataByBusinessRuleDTO.getFormDataList().forEach((item) -> {
                ids.add(item.getDataId());
            });
            if ( !ids.isEmpty() ) {
                paasFormDataModel.deleteBatch(ids, corpid, del);
            }
        } catch (Exception e) {
            LOG.error("formData.deleteFormDataByBusinessRule根据业务规则删除数据出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return deleteFormDataByBusinessRuleVO;
    }

    //==================== private method ====================


    /**
     * 根据用户具有的该表单的权限显隐详情上部操作按钮
     * TODO 考虑协同人情况，需整理思路，目前只处理了操作权限
     *
     * @param userFormPermissionVO 用户具有的该表单的权限
     * @param del                  删除标记，0表示正常数据，1表示回收站数据，3表示彻底删除数据
     */
    private List<ButtonPojo> setDetailButtonPermission(UserFormPermissionVO userFormPermissionVO, String platform, int del) {
        // 已彻底删除的数据不应有任何操作，正常情况下也不应该暴露
        List<ButtonPojo> buttonList = new ArrayList<>();
        if ( del >= DelEnum.REMOVE_COMPLETELY.getDel() ) {
            return buttonList;
        }

        PermissionTermsPojo permissionTerms = userFormPermissionVO.getFormPermission().getPermission();
        // 上部按钮权限
        Boolean isAdmin = userFormPermissionVO.getIsAdminOrBoss();
        // 注意顺序
        if ( del == 0 && (permissionTerms.getCreate().equals(1) || isAdmin) ) {
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(SaasButtonEnum.COPY, buttonPojo);
            buttonList.add(buttonPojo);
        }
        if ( del == 0 && (permissionTerms.getUpdate().equals(1) || isAdmin) ) {
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(SaasButtonEnum.EDIT, buttonPojo);
            buttonList.add(buttonPojo);
        }
        // 只有web端有打印
        if ( del == 0  && (permissionTerms.getPrint().equals(1) || isAdmin) ) {
            ButtonPojo buttonPojo = new ButtonPojo();
            if (Objects.equals(PlatFormEnum.WEB.getValue(), platform)){
                BeanUtil.copyProperties(SaasButtonEnum.PRINT, buttonPojo);
            } else {
                buttonPojo.setAttr(PaasConstant.PRINTSTRING);
                buttonPojo.setValue(I18nMessageUtil.getMessage(PaasConstant.PRINT));
            }

            buttonList.add(buttonPojo);
        }
        if ( del == 0 && (permissionTerms.getDelete().equals(1) || isAdmin) ) {
            ButtonPojo buttonPojo = new ButtonPojo();
            BeanUtil.copyProperties(SaasButtonEnum.DEL, buttonPojo);
            buttonList.add(buttonPojo);
        }
        return buttonList;
    }

    @Override
    public PaasFormDataEsListVO getBusinessDataList(BusinessDataDTO businessDataDTO) throws XbbException {
        PaasFormDataEsListVO formDataListVO;
        try {
            if (businessDataDTO.getBusinessType().equals(XbbRefTypeEnum.PRODUCT_WAREHOUSE.getCode())){
                return productStockInfoService.getProductWarehouse(businessDataDTO);
            }
            String corpid = businessDataDTO.getCorpid();
            Integer type = businessDataDTO.getType();
            Integer businessType = businessDataDTO.getBusinessType();
            Integer businessType4Distributor = XbbRefTypeEnum.transferBusinessType4Distributor(businessType, businessDataDTO.getDistributorMark());
            Integer sourceBusinessType = businessDataDTO.getSourceBusinessType();
            Long formId = businessDataDTO.getFormId();
            PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
            //查询表单数据，用于获取summary,labels，customerList信息
            PaasFormEntityExt form = new PaasFormEntityExt();
            if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(formId, corpid);
                WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, corpid);

                BeanUtil.copyProperties(workOrderExplainEntityExt, paasFormExplainEntity);
                BeanUtil.copyProperties(workOrderFormEntityExt, form);
            } else {
                paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
                form = paasFormModel.getByKey(formId,corpid);
            }
            if ( paasFormExplainEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            businessDataDTO.setDistributorMark(paasFormExplainEntity.getDistributorMark());
            // 退货退款的关联单据是退货退款单
            if ( Objects.equals(paasFormExplainEntity.getBusinessType(), XbbRefTypeEnum.REFUND.getCode()) ) {
                businessType = XbbRefTypeEnum.REFUND.getCode();
                businessDataDTO.setBusinessType(businessType);
            }
            if ( sourceBusinessType != null && Objects.equals(businessDataDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && Objects.equals(sourceBusinessType, XbbRefTypeEnum.PRODUCT.getCode()) ) {
                Boolean isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), businessDataDTO.getCorpid());
                if ( !isJxcUse ) {
                    throw new XbbException(ProductErrorCodeEnum.API_ERROR_205041);
                }
            }
            FormDataListDTO formDataListDTO = new FormDataListDTO();
            BeanUtil.copyProperties(businessDataDTO, formDataListDTO, true);
            // 导入需要查多模板数据
            if ( CollectionsUtil.isNotEmpty(businessDataDTO.getFormIdList()) ) {
                formDataListDTO.setLimitForms(true);
                formDataListDTO.setFormIdList(businessDataDTO.getFormIdList());
            }
            // 统一设置审批状态，默认只获取0（无需审批）,2（审批通过）状态的数据，有特殊的在specialHandleConditions中特殊设置
            formDataListDTO.getConditions().add(new ConditionsEntityExt(FieldTypeEnum.FLOW_STATUS.getAlias(), "", FieldTypeEnum.FLOW_STATUS.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
            // 只能搜到没有删除的数据
            formDataListDTO.setDel(0);

            formDataListDTO.setSimple(false);
            List<Long> dataIdIn = businessDataDTO.getIdIn();
            if ( dataIdIn != null && !dataIdIn.isEmpty() ) {
                formDataListDTO.getConditions().add(EsUtil.packageContions(StringConstant.DATA_ID, new ArrayList<>(dataIdIn), ConditionEnum.IN, FieldTypeEnum.DATAID.getType()));
            }

            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            Map<String, FieldAttrEntity> explainMap = paasFormExplainService.getExpalinMap(explainList, paasFormExplainEntity.getBusinessType(), corpid,paasFormExplainEntity.getFormId());
            // 关联业务约束条件
            setParentBusinessType(businessDataDTO, formDataListDTO);
            // 特殊逻辑限制，出入库单选择单据等
            specialHandleConditions(businessDataDTO, formDataListDTO);
            if ( Objects.equals(SaasMarkEnum.SAAS.getCode(), businessDataDTO.getSaasMark()) ) {
                List<ConditionsEntityExt> conditionList = businessDataDTO.getConditions();
                if ( Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.WAREHOUSE.getCode())  || Objects.equals(businessType, XbbRefTypeEnum.COMPETITOR.getCode())) {
                    saasListDataPermissionHelp.listDepAndUserDataPermission(businessDataDTO.getShouldConditions(), businessDataDTO.getLoginUser(), businessType, businessDataDTO.getLoginUser().getDepSet());
                } else if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                    workOrderListDataPermissionHelp.listDataPermission(conditionList, businessDataDTO.getShouldConditions(), businessDataDTO.getLoginUser(), 0, 0L);
                    businessDataDTO.setConditions(conditionList);
                } else  {
                    Boolean needCheckPermission = true;
                    if (Objects.equals(businessType, XbbRefTypeEnum.CONTACT.getCode()) && Objects.equals(businessDataDTO.getParentBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                        CustomerEntityExt customerEntityExt = customerModel.getByKey(businessDataDTO.getParentId(), corpid);
                        if (Objects.nonNull(customerEntityExt) && Objects.equals(customerEntityExt.getDel(),DelEnum.NORMAL.getDel())) {
                            Integer isPublic = customerEntityExt.getData().getInteger(CustomerManagementEnum.IS_PUBLIC.getAttr());
                            if (Objects.equals(isPublic, 1)) {
                                // 联系人，如果他关联的客户是公海客户，那么就不校验团队
                                needCheckPermission = false;
                            }
                        }
                    }
                    if (needCheckPermission) {
                        List<ConditionsEntityExt> permissionConditions = saasListDataPermissionHelp.listDataPermission(false, conditionList, businessDataDTO.getLoginUser(), businessType, businessDataDTO.getSubBusinessType());
                        // 共享权限处理
                        ShareConditionFormatPojo sharePermission = saasListDataPermissionHelp.getSharePermission(permissionConditions, Collections.singletonList(businessDataDTO.getFormId()), businessDataDTO.getLoginUser());
                        formDataListDTO.setSharePermission(sharePermission);
                    }
                    businessDataDTO.setConditions(conditionList);
                }
            }
            formDataListDTO.setExplainMap(explainMap);
            // 显示的字段，先取表里的字段
            LinkBusinessGetVO linkBusinessGetVO = proLinkBusinessService.getByLinkFormId(corpid, businessDataDTO.getAttr(),
                    businessDataDTO.getThisFormId(), formId, sourceBusinessType);
            List<String> fieldList = linkBusinessGetVO.getFieldList();
            if (CollectionUtils.isNotEmpty(fieldList) && Objects.nonNull(explainMap)) {
                for (String fieldAttr : fieldList) {
                    FieldAttrEntity fieldAttrEntity = explainMap.get(fieldAttr);
                    if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType()) && !fieldList.contains(PaasStageEnum.STAGE_PROCESS_ID.getAttr())) {
                        fieldList.add(PaasStageEnum.STAGE_PROCESS_ID.getAttr());
                        break;
                    }
                }
            }
            String jxcParentAttr = null;
            //变量冲突,资金管理加的parentAttr
            String parentAttr = null;
            String invoiceAmountAttr = null;
            boolean oriFieldListNoContain = false;

            if (Objects.isNull(fieldList) || fieldList.isEmpty()) {
                fieldList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//                if(Objects.equals(XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode(),XbbRefTypeEnum.transferBusinessType4Distributor(businessType,formDataListDTO.getDistributorMark())) && Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
//                    //订货单里的关联经销商档案要带出，默认收货人、收货地址
//                    fieldList.addAll(BusinessFieldEnum.getByBusinessType(XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode()));
//                } else if(Objects.equals(XbbRefTypeEnum.WAREHOUSE.getCode(),formDataListDTO.getBusinessType()) && Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())){
//                    //订货单中里的关联仓库要带出，收货人、收货地址
//                    fieldList.addAll(BusinessFieldEnum.getByBusinessType(businessType));
//                    fieldList.add(WarehouseEnum.SENDER_INFORMATION.getAttr());
//                    fieldList.add(WarehouseEnum.SENDER_DETAILS.getAttr());
//                }else {
                    fieldList.addAll(BusinessFieldEnum.getByBusinessType(businessType));
//                }
                fieldList = saasListHelp.dealFieldList(fieldList, businessType, businessDataDTO.getSourceBusinessType(), type);
            }else {
                // ES限定返回字段
                if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode()) || Objects.equals(sourceBusinessType,XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode()) ||Objects.equals(sourceBusinessType,XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode()) ){
                    if (!fieldList.contains(ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr())){
                        fieldList.add(ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr());
                        fieldList.add(ProductionOrderEnum.INTO_WAREHOUSE_ID_LINK_TEXT.getAttr());
                    }
                    if (!fieldList.contains(ProductionOrderEnum.OUT_WAREHOUSE_ID.getAttr())){
                        fieldList.add(ProductionOrderEnum.OUT_WAREHOUSE_ID.getAttr());
                        fieldList.add(ProductionOrderEnum.OUT_WAREHOUSE_ID_LINK_TEXT.getAttr());
                    }

                }

                //客户线索机会表单需要返回阶段流程id
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(sourceBusinessType, XbbRefTypeEnum.CLUE.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
                    if (fieldList.contains(CustomerManagementEnum.CUSTOMER_STAGE.getAttr()) || fieldList.contains(ClueEnum.CLUE_STAGE.getAttr()) || fieldList.contains(SalesOpportunityEnum.SALE_STAGE.getAttr())) {
                        fieldList.add(PaasStageEnum.STAGE_PROCESS_ID.getAttr());
                    }
                }
            }
            fieldList = new ArrayList<>(fieldList);
            if (Objects.nonNull(businessDataDTO.getParentBusinessType())) {
                for (FieldAttrEntity fieldAttrEntity : explainList) {
                    if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())
                            && Objects.equals(fieldAttrEntity.getLinkedType(), businessDataDTO.getParentBusinessType())) {
                        jxcParentAttr = fieldAttrEntity.getAttr();
                        if (!fieldList.contains(jxcParentAttr)) {
                            oriFieldListNoContain = true;
                            fieldList.add(fieldAttrEntity.getAttr());
                            if (Objects.nonNull(fieldAttrEntity.getLinkedText())) {
                                fieldList.add(fieldAttrEntity.getLinkedText());
                            }
                        }
                        break;
                    }
                }
            }
//            if (fieldList.isEmpty()) {
//                fieldList = new ArrayList<>(BusinessFieldEnum.getByBusinessType(businessType));
//                if (Objects.nonNull(businessDataDTO.getParentBusinessType())) {
//                    for (FieldAttrEntity fieldAttrEntity : explainList) {
//                        if (Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LINK_BUSINESS_SINGLE.getType())
//                                && Objects.equals(fieldAttrEntity.getLinkedType(), businessDataDTO.getParentBusinessType())) {
//                            jxcParentAttr = fieldAttrEntity.getAttr();
//                            if (!fieldList.contains(jxcParentAttr)) {
//                                oriFieldListNoContain = true;
//                                fieldList.add(fieldAttrEntity.getAttr());
//                                if (Objects.nonNull(fieldAttrEntity.getLinkedText())) {
//                                    fieldList.add(fieldAttrEntity.getLinkedText());
//                                }
//                            }
//                            break;
//                        }
//                    }
//                }
//                fieldList = saasListHelp.dealFieldList(fieldList, businessType, businessDataDTO.getSourceBusinessType(), type);
//            }

            if ( Objects.equals(businessDataDTO.getBusinessType(), XbbRefTypeEnum.CONTRACT.getCode()) ) {
                invoiceAmountAttr = ContractEnum.INVOICE_AMOUNT.getAttr();
                fieldList.add(invoiceAmountAttr);
            }
            //出库发货单中的关联订单要带出收货人、收货地址
            if(Objects.equals(XbbRefTypeEnum.ORDER.getCode(),XbbRefTypeEnum.transferBusinessType4Distributor(businessType,formDataListDTO.getDistributorMark())) && Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())){
                fieldList.add(OrderEnum.LINK_PARTNER_RECEIVER.getAttr());
                fieldList.add(OrderEnum.LINK_PARTNER_RECEIVER_HIDE.getAttr());
                fieldList.add(OrderEnum.LINK_CONTACT_NUMBER.getAttr());
                fieldList.add(OrderEnum.SHIPPING_ADDRESS.getAttr());
            }
            //if (CollectionsUtil.isNotEmpty(businessDataDTO.getParentIdList())) {
            if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.INVOICE.getCode())) {
                if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT_SHEET.getCode())) {
                    invoiceAmountAttr = PaymentSheetEnum.INVOICE_AMOUNT.getAttr();
                    fieldList.add(BasicConstant.UUID);
                    fieldList.add(BasicConstant.ALONE);
                    fieldList.add(invoiceAmountAttr);
                }
            }else if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                if (Objects.equals(businessType, XbbRefTypeEnum.PAY_SHEET.getCode())) {
                    invoiceAmountAttr = PaySheetEnum.INVOICE_AMOUNT.getAttr();
                    fieldList.add(BasicConstant.UUID);
                    fieldList.add(BasicConstant.ALONE);
                    fieldList.add(invoiceAmountAttr);
                }
            }

            formDataListDTO.setFieldList(fieldList);
            List<LinkConditionPoJo> conditionList = linkBusinessGetVO.getConditionList();
            if ( Objects.nonNull(linkBusinessGetVO) && CollectionsUtil.isNotEmpty(conditionList) && MapUtils.isNotEmpty(businessDataDTO.getData())) {
                // 获取对应的条件
                JSONObject data = businessDataDTO.getData();
                List<LinkConditionDataDTO> conditionDataList = new ArrayList<>();
                conditionList.forEach(item -> {
                    Object value = data.get(item.getAttr());
                    LinkConditionDataDTO linkConditionDataDTO = new LinkConditionDataDTO();
                    linkConditionDataDTO.setAttr(item.getAttr());
                    linkConditionDataDTO.setValue(value);
                    if (Objects.nonNull(item.getValueType())) {
                        linkConditionDataDTO.setSymbol(item.getSymbol());
                        linkConditionDataDTO.setValueType(item.getValueType());
                    }
                    conditionDataList.add(linkConditionDataDTO);
                });
                // 获取当前表单的字段信息
                PaasFormExplainEntity thisExplain = proFormHelp.getExplainEntity(corpid, businessDataDTO.getThisFormId(), businessDataDTO.getSourceBusinessType());
                Map<String, FieldAttrEntity> thisExplainMap = ExplainUtil.getExplainMap(thisExplain.getExplains(), null);
                // 根据当前表单的字段信息获取字段：数据集合
                Map<String, Object> valueMap = baseLinkBoolQueryBuilderService.getValueMap(thisExplainMap, conditionDataList, null, corpid);
                // 根据当前表单和关联表单的字段，以及数据整理出需要搜索的条件
                ConditionDTO conditionDTO = new ConditionDTO();
                BeanUtil.copyProperties(businessDataDTO, conditionDTO);
                // 增加一个id字段
                FieldAttrEntity dataIdFieldAttrEntity = new FieldAttrEntity();
                dataIdFieldAttrEntity.setAttr(FieldTypeEnum.DATAID.getAlias());
                dataIdFieldAttrEntity.setAttrName(FieldTypeEnum.DATAID.getAlias());
                dataIdFieldAttrEntity.setFieldType(FieldTypeEnum.DATAID.getType());
                explainMap.put(FieldTypeEnum.DATAID.getAlias(), dataIdFieldAttrEntity);
                thisExplainMap.put(FieldTypeEnum.DATAID.getAlias(), dataIdFieldAttrEntity);
                conditionDTO.setRelyExplainMap(explainMap);
                conditionDTO.setExplainMap(thisExplainMap);
                conditionDTO.setBusinessType(businessDataDTO.getSourceBusinessType());
                conditionDTO.setFormId(businessDataDTO.getThisFormId());
                conditionDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
                conditionDTO.setLinkBusinessType(businessType);
                conditionDTO.setLinkFormId(formId);
                conditionDTO.setLinkSaasMark(SaasMarkEnum.SAAS.getCode());
                conditionDTO.setValueMap(valueMap);
                conditionDTO.setCondition(conditionList);
                conditionDTO.setList(formDataListDTO.getConditions());
                List<ConditionsEntityExt> resultCondition = proConditionHelp.getConditionList(conditionDTO);
                formDataListDTO.setConditions(resultCondition);
            }
            formDataListDTO.setSaasMark(businessDataDTO.getSaasMark());
            // 生产单选择关联BOM单时产品名称字段特殊处理
            if ( Objects.equals(businessType, XbbRefTypeEnum.BOM_BILL.getCode()) && Objects.equals(businessDataDTO.getSourceBusinessType(), XbbRefTypeEnum.PRODUCTION_ORDER.getCode()) ) {
                explainList.forEach(explain -> {
                    if ( Objects.equals(explain.getAttr(), BomBillEnum.PRODUCT_NAME_HIDE.getAttr()) ) {
                        explain.setShowType(ShowTypeEnum.LIST.getCode());
                        explain.setAttrName(BomBillEnum.PRODUCT_NAME.getAttrName());
                    }else if (Objects.equals(explain.getAttr(),BomBillEnum.PRODUCT_NO.getAttr())){
                        explain.setShowType(ShowTypeEnum.LIST.getCode());
                    }else if (Objects.equals(explain.getAttr(),BomBillEnum.PRODUCT_SPECIFICATION.getAttr())){
                        explain.setShowType(ShowTypeEnum.LIST.getCode());
                    }
                });
                // 查询条件加上产品编号
                String categoryIdStr = businessDataDTO.getCategoryId();
                if ( !StringUtil.isEmpty(categoryIdStr) && !"0".equals(categoryIdStr) ) {
                    Long categoryId = Long.valueOf(categoryIdStr);
                    // 查询产品id, 并添加到查询条件中
                    List<Object> dataIdList = getProductIds(corpid, categoryId);
                    List<ConditionsEntityExt> productConditionList = new ArrayList<>();
                    productConditionList.add(new ConditionsEntityExt(BomBillEnum.PRODUCT_NAME.getAttr(),"", BomBillEnum.PRODUCT_NAME.getFieldType(),ConditionEnum.IN.getSymbol(), dataIdList));
//                    formDataListDTO.setConditions(productConditionList);
                    //在筛选时加入判断条件
                    formDataListDTO.getConditions().add(productConditionList.get(0));
                }
            }
            // ES 查询
            //移动端app关联数据展示字段多,查询es时,对返回的field不做限制
            if(PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform())){
                formDataListDTO.setFieldList(null);
            }
            // 不检索出子表单
            formDataListDTO.setSearchSubForm(false);
            //如果是出库退货单中关联订货单，这个订货单的订单状态有要求,订单状态必须为待发货
            if (Objects.equals(businessDataDTO.getSourceBusinessType(),XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()) && Objects.equals(XbbRefTypeEnum.transferBusinessType4Distributor(formDataListDTO.getBusinessType(),formDataListDTO.getDistributorMark()),XbbRefTypeEnum.ORDER.getCode())) {
                List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions();
                conditionsEntityExtList = conditionsEntityExtList == null ? new ArrayList<>() : conditionsEntityExtList;
                ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(OrderEnum.STATUS.getAttr(), "", OrderEnum.STATUS.getFieldType(), ConditionEnum.EQUAL.getSymbol(), Arrays.asList(OrderStatusEnum.DELIVERED.getCode()));
                conditionsEntityExtList.add(conditionsEntityExt);
                formDataListDTO.setConditions(conditionsEntityExtList);
            }
            // 如果是合同下新建应收款，则只查询未收金额不等于0的数据
            if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType) && Objects.equals(XbbRefTypeEnum.PAYMENT.getCode(), businessDataDTO.getSourceBusinessType())) {
                List<ConditionsEntityExt> conditionsEntityExts = formDataListDTO.getConditions();
                conditionsEntityExts.add(new ConditionsEntityExt(ContractEnum.UN_FINISH_AMOUNT.getAttr(), "", FieldTypeEnum.NUM.getType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(0)));
                formDataListDTO.setConditions(conditionsEntityExts);
            }
            // 地址查询条件封装
            saasListHelp.addressSearchCondition(formDataListDTO);
            IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(formDataListDTO.getCorpid(), formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
            formDataListVO = paasFormDataEsModel.list(formDataListDTO, indexTypeEnum);
            //如果是订单中的关联经销商档案要带出默认的地址
//            if (Objects.equals(XbbRefTypeEnum.transferBusinessType4Distributor(formDataListDTO.getBusinessType(),formDataListDTO.getDistributorMark()),XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode()) && Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())){
//                List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
//                paasFormDataESList.forEach(paasFormDataEntityExt->{
//                    JSONObject data = paasFormDataEntityExt.getData();
//                    if (Objects.nonNull(data)){
//                        JSONArray shippingAddress = data.getJSONArray(DistributorEnum.SHIPPING_ADDRESS.getAttr());
//                        if (Objects.nonNull(shippingAddress)){
//                            shippingAddress.removeIf(item -> Objects.nonNull(item) && Objects.equals(((JSONObject) JSON.toJSON(item)).get(DistributorAddressEnum.SET_DEFAULT.getAttr()),0));
//                            data.put(DistributorEnum.SHIPPING_ADDRESS.getAttr(),shippingAddress);
//                        }
//                    }
//                });
//            }
            //判断发票或退货退款业务下对回款单类型的特殊处理
            if (Objects.equals(sourceBusinessType,XbbRefTypeEnum.PURCHASE_INVOICE.getCode()) || Objects.equals(sourceBusinessType, XbbRefTypeEnum.INVOICE.getCode()) || Objects.equals(sourceBusinessType, XbbRefTypeEnum.REFUND.getCode())) {
                List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
                List<Long> paymentSheetIdIn = new ArrayList<>();
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    JSONObject data = paasFormDataEntityExt.getData();
                    if(Objects.equals(businessType, XbbRefTypeEnum.PAYMENT_SHEET.getCode())) {
                        String paymentSheetType = FastJsonHelper.getStringOrDefaultFromFormData(data, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), PaymentSheetTypeEnum.UNKNOWN.getCode());
                        data.put(InvoiceConstant.PAYMENT_SHEET_TYPE, paymentSheetType);
                    }else if(Objects.equals(businessType, XbbRefTypeEnum.PAY_SHEET.getCode())){
                        String paySheetType = FastJsonHelper.getStringOrDefaultFromFormData(data, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), PaySheetTypeEnum.UNKNOWN.getCode());
                        data.put(InvoiceConstant.PAY_SHEET_TYPE, paySheetType);
                    }
                    paymentSheetIdIn.add(paasFormDataEntityExt.getDataId());
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT_SHEET.getCode()) && paymentSheetIdIn.size() > 0) {
                    removeRedPaymentSheetByRedAmount(corpid, paymentSheetIdIn, paasFormDataESList);
                }
            }
            //判断采购退货逻辑下对付款单类型的特殊处理
            if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_PURCHASE.getCode()) && Objects.equals(businessType, XbbRefTypeEnum.PAY_SHEET.getCode())) {
                List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
                List<Long> paymentSheetIdIn = new ArrayList<>();
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    paymentSheetIdIn.add(paasFormDataEntityExt.getDataId());
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.PAY_SHEET.getCode()) && paymentSheetIdIn.size() > 0) {
                    removeRedPaySheetByRedAmount(corpid, paymentSheetIdIn, paasFormDataESList);
                }
            }
            if ( parentAttr != null && invoiceAmountAttr != null ) {
                fieldList.remove(parentAttr);
                fieldList.remove(invoiceAmountAttr);
                fieldList.remove(BasicConstant.UUID);
                fieldList.remove(BasicConstant.ALONE);
            } else if ( invoiceAmountAttr != null ) {
                fieldList.remove(invoiceAmountAttr);
                fieldList.remove(BasicConstant.UUID);
                fieldList.remove(BasicConstant.ALONE);
            }

            PaasFormEntityExt formEntityExt = new PaasFormEntityExt();
            BeanUtil.copyProperties(formDataListDTO, formEntityExt);
            formEntityExt.setId(formDataListDTO.getFormId());
            //app移动端需要查询所有数据，explainList不能缺失字段，不进行字段remove
            if( Objects.equals(PlatFormEnum.WEB.getValue(),formDataListDTO.getPlatform()) ) {
                explainList = explainHelp.handleExplain(explainList, fieldList, formEntityExt);
                Iterator<FieldAttrEntity> iterator = explainList.iterator();
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    if (ExplainUtil.isSubForm(fieldAttrEntity.getFieldType())) {
                        List<? extends FieldAttrEntity> list = fieldAttrEntity.getSubForm().getItems();
                        Iterator<? extends FieldAttrEntity> subIterator = list.iterator();
                        while (subIterator.hasNext()) {
                            FieldAttrEntity subField = subIterator.next();
                            if (Objects.equals(FieldTypeEnum.LINK_DATA.getType(), subField.getFieldType())) {
                                subIterator.remove();
                                continue;
                            }
                        }
                        if (CollectionsUtil.isEmpty(list)) {
                            iterator.remove();
                            continue;
                        }
                    }
                }
            }
            formDataListVO.setHeadList(explainList);
            /**
             * 处理选择客户时同时获取预收款金额
             */
            Map<Long,String> uuidMap = null;
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                paymentBalanceService.getSupplementAmount(formDataListVO, corpid);
            }
            if(Objects.equals(businessType, XbbRefTypeEnum.PAYMENT_SHEET.getCode())){
                uuidMap = saasSaveHelp.getUuidByPaymentSheet(formDataListVO.getPaasFormDataESList());
            }
            if ( Objects.equals(businessType, XbbRefTypeEnum.SUPPLIER.getCode()) ) {
                payBalanceService.getSupplementAmount(formDataListVO, corpid);
            }
            /**
             * 在新建回款计划时，返回已核销的金额
             */
            if ( (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) && Objects.equals(sourceBusinessType, XbbRefTypeEnum.PAYMENT.getCode()))
                    || (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode()) && Objects.equals(sourceBusinessType, XbbRefTypeEnum.PAY_PLAN.getCode()))){
                FormDataUpdateGetDTO formDataUpdateGetDTO = new FormDataUpdateGetDTO();
                BeanUtil.copyProperties(businessDataDTO,formDataUpdateGetDTO);
                formDataUpdateGetDTO.setSubBusinessType(businessDataDTO.getSourceBusinessType());
                formDataUpdateGetDTO.setBusinessType(businessDataDTO.getBusinessType());
                for ( PaasFormDataEntityExt paasFormDataEntityExt : formDataListVO.getPaasFormDataESList() ) {
                    formDataUpdateGetDTO.setDataId(paasFormDataEntityExt.getId());
                    //合同金额=(预收款核销金额+回款单核销金额)+回款计划金额-回款计划已收金额-回款计划已坏金额+(坏账金额+已红冲金额)
                    //采购金额=预付款核销金额+回款单核销金额+付款计划金额-付款计划已付金额-付款计划已坏金额+坏账金额-已红冲预付款金额-已红冲回款单金额
                    Double finishAmount = fundMoneyHelp.getWriteOffAmount(formDataUpdateGetDTO,businessType);
                    paasFormDataEntityExt.setFinishAmount(finishAmount);
                }
            }
            if (Objects.equals(businessDataDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode()) && Objects.equals(businessDataDTO.getSourceBusinessType(), XbbRefTypeEnum.REFUND.getCode())) {
                List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
                List<Long> couponIdList = new ArrayList<>();
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    JSONArray couponId = paasFormDataEntityExt.getData().getJSONArray(OrderEnum.COUPON_ID.getAttr());
                    if (CollectionUtils.isNotEmpty(couponId)) {
                        for (int i = 0; i < couponId.size(); i++) {
                           couponIdList.add(couponId.getLongValue(i));
                        }
                    }
                }
                if (CollectionUtils.isNotEmpty(couponIdList)) {
                    List<CouponEntity> coupons = couponModel.findEntitysByIdIn(couponIdList, corpid);
                    Map<Long, String> couponNameMap = new HashMap<>();
                    coupons.forEach(item -> couponNameMap.put(item.getId(), item.getName()));
                    for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                        JSONArray couponId = paasFormDataEntityExt.getData().getJSONArray(OrderEnum.COUPON_ID.getAttr());
                        if (CollectionUtils.isNotEmpty(couponId)) {
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < couponId.size(); i++) {
                                sb.append(couponNameMap.getOrDefault(couponId.getLongValue(i), ""));
                            }
                            paasFormDataEntityExt.getData().put(ReturnEnum.RETURN_TIPS.getSaasAttr(), sb);
                        }
                    }
                }
            }

            //如果是订货单中的关联经销商档案要带出默认的地址,在headList去除收货地址，防止被format
//            if (Objects.equals(XbbRefTypeEnum.transferBusinessType4Distributor(formDataListDTO.getBusinessType(),formDataListDTO.getDistributorMark()),XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode()) && Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CONTRACT.getCode())) {
//                List<FieldAttrEntity> headList = formDataListVO.getHeadList();
//                if (Objects.nonNull(headList)){
//                    headList.removeIf(item ->Objects.equals(item.getAttr(),DistributorEnum.SHIPPING_ADDRESS.getAttr()));
//                    formDataListVO.setHeadList(headList);
//                }
//            }
            //如果是出库发货单中的关联订货单要带出默认的地址,在headList去除收货地址，防止被format
//            if (Objects.equals(XbbRefTypeEnum.transferBusinessType4Distributor(formDataListDTO.getBusinessType(),formDataListDTO.getDistributorMark()),XbbRefTypeEnum.ORDER.getCode()) && Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())) {
//                List<FieldAttrEntity> headList = formDataListVO.getHeadList();
//                if (Objects.nonNull(headList)){
//                    headList.removeIf(item ->Objects.equals(item.getAttr(),OrderEnum.LINK_PARTNER_RECEIVER.getAttr()) || Objects.equals(item.getAttr(),OrderEnum.SHIPPING_ADDRESS.getAttr()));
//                    formDataListVO.setHeadList(headList);
//                }
//            }
            //如果是出库发货单中的关联仓库要带出默认的地址,在headList去除收货地址，防止被format
//            if (Objects.equals(formDataListDTO.getBusinessType(),XbbRefTypeEnum.WAREHOUSE.getCode()) && Objects.equals(formDataListDTO.getSubBusinessType(),XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())) {
//                List<FieldAttrEntity> headList = formDataListVO.getHeadList();
//                if (Objects.nonNull(headList)){
//                    headList.removeIf(item ->Objects.equals(item.getAttr(),WarehouseEnum.SENDER_INFORMATION.getAttr()) || Objects.equals(item.getAttr(),WarehouseEnum.SENDER_DETAILS.getAttr()));
//                    formDataListVO.setHeadList(headList);
//                }
//            }
            if ( PlatFormEnum.WEB.getValue().equals(formDataListDTO.getPlatform()) ) {
                // 返回数据处理
                saasListHelp.analysisSaasDataList(formDataListVO, explainMap);
                // web端逻辑，主要处理下关于关联数据，用户，部门数据回显的问题
                //选择单据列表就不要这个了，不然会渲染操作栏
                formDataListDTO.setSubBusinessType(null);
                if (Objects.isNull(formDataListVO.getExplainMap())) {
                    formDataListVO.setExplainMap(explainMap);
                }
                formDataListSearchHelp.webDataAnalysis(formDataListDTO, formDataListVO);
            } else if ( PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform()) ) {
                //app端需要对返回结果处理.
                //塞入summaryList, labelList,titleList。
                formDataListVO.setForm(form);
                formDataListVO = formDataListSearchHelp.appDataAnalysis(formDataListDTO, formDataListVO);
                //按照业务类型塞入others,superScript;这里的逻辑是和列表展示保持一致的。eg: 关联客户数据 和 客户列表 的others逻辑是一样的
                formatBusinessDataAppList(formDataListDTO,formDataListVO.getPaasFormDataESList());
            }
            if (StringUtil.isNotEmpty(jxcParentAttr)) {
                for (PaasFormDataEntity paasFormDataEntity : formDataListVO.getPaasFormDataESList()) {
                    paasFormDataEntity.getData().put("refValue", paasFormDataEntity.getData().get(jxcParentAttr));
                }
                if (oriFieldListNoContain) {
                    for (int i = 0; i < formDataListVO.getHeadList().size(); i++) {
                        if (Objects.equals(formDataListVO.getHeadList().get(i).getAttr(), jxcParentAttr)) {
                            formDataListVO.getHeadList().remove(i);
                            break;
                        }
                    }
                }
            }
            // 从弹窗进入，所在地区把FieldType改为text,用于前端渲染
            if (Objects.equals(businessType4Distributor, XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode()) && explainMap.containsKey(DistributorEnum.AREA.getAttr())) {
                FieldAttrEntity areaEntity = explainMap.get(DistributorEnum.AREA.getAttr());
                if (Objects.nonNull(areaEntity) && Objects.equals(areaEntity.getFieldType(), FieldTypeEnum.AREA.getType())) {
                    areaEntity.setFieldType(FieldTypeEnum.TEXT.getType());
                    explainMap.put(DistributorEnum.AREA.getAttr(), areaEntity);
                    formDataListVO.setExplainMap(explainMap);
                }
            }
            // 从弹窗进入，出库发货单关联订货单收货人和签订人FieldType改为text,用于前端渲染
            if (Objects.equals(businessDataDTO.getSourceBusinessType(),XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode()) && Objects.equals(XbbRefTypeEnum.transferBusinessType4Distributor(formDataListDTO.getBusinessType(),formDataListDTO.getDistributorMark()),XbbRefTypeEnum.ORDER.getCode())) {
                FieldAttrEntity receiverEntity = explainMap.get(OrderEnum.LINK_PARTNER_RECEIVER.getAttr());
                FieldAttrEntity signEntity = explainMap.get(OrderEnum.SIGN_PERSON.getAttr());
                if (Objects.nonNull(receiverEntity) && Objects.equals(receiverEntity.getFieldType(), FieldTypeEnum.LINK_RECEIVER.getType())) {
                    receiverEntity.setFieldType(FieldTypeEnum.TEXT.getType());
                    /*explainMap.put(OrderEnum.LINK_PARTNER_RECEIVER.getAttr(), receiverEntity);
                    formDataListVO.setExplainMap(explainMap);*/
                }
                if(Objects.nonNull(signEntity) && Objects.equals(signEntity.getAttr(), OrderEnum.SIGN_PERSON.getAttr())){
                    signEntity.setFieldType(FieldTypeEnum.TEXT.getType());
                    /*explainMap.put(OrderEnum.SIGN_PERSON.getAttr(), receiverEntity);
                    formDataListVO.setExplainMap(explainMap);*/
                }
            }

            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            // 查询数据库菜单名称
            PaasMenuEntity paasMenuEntity;
            if (XbbRefTypeEnum.hasDistributorMenu(businessType)) {
                paasMenuEntity = paasMenuModel.getByAlias4Distributor(XbbRefTypeEnum.getByCode(businessType).getAlias(), corpid, businessDataDTO.getDistributorMark());
            } else {
                paasMenuEntity = paasMenuModel.getByAlias(XbbRefTypeEnum.getByCode(businessType).getAlias(), corpid);
            }
            paasFormEntityExt.setBusinessName(paasMenuEntity.getName());
            String mainAttr = CommonBusinessFieldUtil.getFormEntityMainAttr(businessType);
            paasFormEntityExt.setMainAttr(mainAttr);
            paasFormEntityExt.setId(businessDataDTO.getFormId());
            paasFormEntityExt.setAppId(paasFormExplainEntity.getAppId());
            paasFormEntityExt.setMenuId(paasFormExplainEntity.getMenuId());
            paasFormEntityExt.setFormId(paasFormExplainEntity.getFormId());
            formDataListVO.setForm(paasFormEntityExt);
            List<Long> idList = new ArrayList<>();
            if(Objects.nonNull(businessDataDTO.getParentId())){
                idList.add(businessDataDTO.getParentId());
            }else if(Objects.nonNull(businessDataDTO.getParentIdList())){
                businessDataDTO.getParentIdList().forEach(parentId -> idList.add(Long.valueOf(parentId)));
            }
            //资金管理第一期,因为加了一条去掉可开金额为0的规定,如果合同开完了然后去编辑他,再选合同会选不到
            /*Map<Long,Double> refIdMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if(Objects.nonNull(businessDataDTO.getEditInvoiceId())){
                if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.INVOICE.getCode())) {
                    refIdMap = getEditInvoiceRef(businessDataDTO.getEditInvoiceId(), corpid, businessType);
                }
            }*/
            //等销项发票重构 之后会删除这个方法
            //invoiceRefObjectHandle(parentAttr,corpid,formDataListVO,invoiceAmountAttr,businessDataDTO.getParentBusinessType(),businessType,businessDataDTO.getSourceBusinessType(),idList,uuidMap,refIdMap);
            // 新建权限
            VerifyAddPermissionDTO verifyAddPermissionDTO = new VerifyAddPermissionDTO();
            BeanUtil.copyProperties(businessDataDTO, verifyAddPermissionDTO);
            verifyAddPermissionDTO.setBusinessType(businessType);
            verifyAddPermissionDTO.setMenuId(paasFormExplainEntity.getMenuId());
            verifyAddPermissionDTO.setSaasMark(paasFormExplainEntity.getSaasMark());
            List<ButtonPojo> buttonList = paasFormHelp.getAddButton(verifyAddPermissionDTO, paasFormExplainEntity.getAppId(), paasFormExplainEntity.getFormId());
            formDataListVO.setTopPermissions(buttonList);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("formDataService.getBusinessDataList 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        formDataListVO.setExplainMap(new HashMap<>());
        return formDataListVO;
    }

    /**
     * 关联数据，格式化为和列表保持一致
     * @param formDataListDTO
     * @param formDataList
     * @throws XbbException
     */
    private void formatBusinessDataAppList(FormDataListDTO formDataListDTO,List<PaasFormDataEntityExt> formDataList) throws XbbException {
        //主业务类型
        Integer businessType = formDataListDTO.getBusinessType();
        int totalCount = formDataList.size();
        if(CollectionsUtil.isNotEmpty(formDataList)){
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            switch (xbbRefTypeEnum){
                //客户
                case CUSTOMER_MANAGEMENT:
                    customerService.formatCustomerAppList(formDataListDTO,formDataList,totalCount);
                    break;
                //合同
                case CONTRACT:
                    contractService.formatContractAppList(formDataListDTO,formDataList,totalCount);
                    break;
                //销售机会
                case SALES_OPPORTUNITY:
                    opportunityService.formatOpportunityAppList(formDataListDTO,formDataList,totalCount);
                    break;
                case SUPPLIER:
                    setSupplierOthersAndSuperScript(formDataListDTO,formDataList);
                    break;
                //采购合同
                case PURCHASE:
                    setPurchaseOthersAndSuperScript(formDataList);
                    break;
                // 生产商
                case PRODUCTION_ORDER:
                    setProductionOrderOthersAndSuperScript(formDataList);
                    break;
                //回款单
                case PAYMENT_SHEET:
                    paymentSheetService.formatPaymentSheetAppList(formDataListDTO,formDataList,totalCount);
                    break;
                //回款计划
                case PAYMENT:
                    paymentService.formatPaymentAppList(formDataListDTO,formDataList,totalCount);
                    break;
                //付款单
                case PAY_SHEET:
                    payPlanSheetService.formatPaySheetAppList(formDataListDTO,formDataList,totalCount);
                    break;
                //付款计划
                case PAY_PLAN:
                    setPayPlanOthersAndSuperScript(formDataList);
                    break;
                    //退货退款
                case REFUND:
                    refundService.formatRefundAppList(formDataListDTO,formDataList,totalCount);
                    break;
                //报价单
                case QUOTATION:
                    quotationService.formatQuotationAppList(formDataListDTO,formDataList,totalCount);
                    break;
                //销售线索
                case CLUE:
                    clueService.formatClueAppList(formDataListDTO,formDataList,totalCount);
                    break;
                //市场活动
                case MARKET_ACTIVITY:
                    marketActivityService.formatMarketActivityAppList(formDataListDTO,formDataList,totalCount);
                    break;
                // 仓库、联系人  都是不需要特殊处理的，默认给一个空值
                case WAREHOUSE:
                case CONTACT:
                default:
                    setDefaultOthersAndSuperScript(formDataList);
                    break;
            }
        }
    }

    private void setPayPlanOthersAndSuperScript(List<PaasFormDataEntityExt> formDataList) throws XbbException {
        for (PaasFormDataEntityExt formDataItem : formDataList) {
            JSONObject formData = formDataItem.getData();
            JSONObject others = new JSONObject();
            String status = FastJsonHelper.getStringOrDefaultFromFormData(formData, PayPlanEnum.STATUS.getAttr(), "");
            others.put(StringConstant.STATUS, status);

            String payAmount = FastJsonHelper.getStringOrDefaultFromFormData(formData, PayPlanEnum.AMOUNT.getAttr(), "0.0");
            Integer isBad = 0;
            if ( Objects.equals(PayPlanStatusEnum.getByAlias(status),PayPlanStatusEnum.BAD_DEBT)
                    || Objects.equals(PayPlanStatusEnum.getByAlias(status),PayPlanStatusEnum.PARTIAL_BAD_DEBT)){
                isBad = 1;
            }
            payAmount = payAmount + UnitEnum.MONEY.getName();
            commonHelp.setPaymentOthers(others, payAmount, status, null,isBad);

            List<SummaryDataPoJo> summaryList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.SUMMARY_LIST, new JSONArray()).toJavaList(SummaryDataPoJo.class);
            List<FormTitlePoJo> titleList = FastJsonHelper.getJsonArrOrDefaultFromFormData(formData, BasicConstant.TITLE_LIST, new JSONArray()).toJavaList(FormTitlePoJo.class);
            if ( Objects.equals(status, PayPlanStatusEnum.UN_RECEIVABLES.getAlias()) || Objects.equals(status, PayPlanStatusEnum.PARTIAL_RECEIPTS.getAlias()) ) {
                for ( SummaryDataPoJo summaryDataPoJo : summaryList ) {
                    String attr = summaryDataPoJo.getAttr();
                    if ( Objects.equals(attr, PayPlanEnum.ESTIMATE_TIME.getAttr()) ) {
                        List<Object> valueList = summaryDataPoJo.getValue();
                        if ( valueList.isEmpty() ) {
                            break;
                        }
                        String valueKey = (String) valueList.get(0);
                        Long estimate = DateTimeUtil.getInt(valueKey, DateTimeUtil.SDFDate);
                        if ( estimate < DateTimeUtil.getTodayInt() ) {
                            summaryDataPoJo.setStatus("delay");
                        }
                        break;
                    }
                }
            }
            if (titleList.isEmpty()) {
                FormTitlePoJo titlePoJo = new FormTitlePoJo();
                titlePoJo.setValue(Collections.singletonList(formDataItem.getSerialNo()));
                titleList.add(titlePoJo);
            }
            formData.put("summaryList",summaryList);
            formData.put("titleList",titleList);
            formData.put("others",others);
        }
    }

    private void setPurchaseOthersAndSuperScript(List<PaasFormDataEntityExt> formDataList) throws XbbException {
        for(PaasFormDataEntityExt purchaseEntityExt : formDataList){
            JSONObject data = purchaseEntityExt.getData();
            JSONObject others = new JSONObject();
            String totalAmount = FastJsonHelper.getStringOrDefaultFromFormData(data, ContractEnum.AMOUNT.getAttr(), "");
            if (!StringUtil.isEmpty(totalAmount)) {
                totalAmount += UnitEnum.MONEY.getName();
            }
            others.put(ContractEnum.AMOUNT.getSaasAttr(), totalAmount);

            fillDataOthersAndSuperScript(purchaseEntityExt,others,new JSONObject());
        }
    }


    private void setProductionOrderOthersAndSuperScript(List<PaasFormDataEntityExt> formDataList) throws XbbException {
        for(PaasFormDataEntityExt procuctionOrderEntity : formDataList){
            JSONObject formData = procuctionOrderEntity.getData();
            JSONObject others = new JSONObject();
            Long now = DateTimeUtil.getTodayInt();
            Long completeTime = FastJsonHelper.getLongOrDefaultFromFormData(formData, ProductionOrderEnum.COMPLETE_TIME.getAttr(), 0L);
            Long closeTime = FastJsonHelper.getLongOrDefaultFromFormData(formData, ProductionOrderEnum.CLOSE_TIME.getAttr(), 0L);
            Long planTime = FastJsonHelper.getLongOrDefaultFromFormData(formData, ProductionOrderEnum.PLAN_TIME.getAttr(), 0L);
            String status4Show = FastJsonHelper.getStringOrDefaultFromFormData(formData, ProductionOrderEnum.STATUS.getAttr(), "");
            ProductionOrderStatusEnum statusEnum = ProductionOrderStatusEnum.getByAlias(status4Show);
            boolean overdue = (Objects.equals(statusEnum, ProductionOrderStatusEnum.UNFINISHED) && now > planTime && planTime != 0L)
                    || (Objects.equals(statusEnum, ProductionOrderStatusEnum.FINISHED) && completeTime > planTime && completeTime != 0L)
                    || (Objects.equals(statusEnum, ProductionOrderStatusEnum.CLOSED) && closeTime > planTime && closeTime != 0L);
            if (overdue) {
                others.put("color", "red");
            }

            String status = ItemUtil.parseItemPoJoFromFormData2String(formData, ProductionOrderEnum.STATUS.getAttr(), "");
            others.put(StringConstant.STATUS, status);

            fillDataOthersAndSuperScript(procuctionOrderEntity,others,new JSONObject());
        }
    }

    private void fillDataOthersAndSuperScript(PaasFormDataEntityExt entityExt , JSONObject others , JSONObject superScript){
        entityExt.getData().put("others",others);
        entityExt.getData().put("superScript" ,superScript);
    }

    private void setDefaultOthersAndSuperScript(List<PaasFormDataEntityExt> formDataList){
        JSONObject jsonObject = new JSONObject();
        formDataList.forEach(entityExt-> {
            fillDataOthersAndSuperScript(entityExt,jsonObject,jsonObject);
        });
    }

    private void setSupplierOthersAndSuperScript(FormDataListDTO formDataListDTO ,List<PaasFormDataEntityExt> formDataList) throws XbbException {
        String corpid = formDataListDTO.getCorpid();
        for (PaasFormDataEntityExt supplierEntity : formDataList) {
            //字段解释
            //其他（右上角，右下角等特殊位置）
            JSONObject others = new JSONObject();
            //特殊标签
            String communicateTimeInterval = I18nMessageUtil.getMessage(StringConstant.NEVER_CONNECT);
            EsDataDTO esDataDTO = new EsDataDTO();
            esDataDTO.setCorpid(corpid);
            esDataDTO.setDel(0);
            esDataDTO.setBusinessType(XbbRefTypeEnum.SUPPLIER_COMMUNICATE.getCode());
            esDataDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
            esDataDTO.setFieldList(null);
            esDataDTO.setPage(1);
            esDataDTO.setPageSize(1);
            Map<String, String> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            sortMap.put(SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr(), StringConstant.SORT_DESC_TAG);
            esDataDTO.setSortMap(sortMap);
            List<ConditionsEntityExt> conditionsEntityExtList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            conditionsEntityExtList.add(EsUtil.packageContions(SupplierCommunicateEnum.SUPPLIER_ID.getAttr(),
                    Collections.singletonList(supplierEntity.getDataId()), ConditionEnum.EQUAL, SupplierCommunicateEnum.SUPPLIER_ID.getFieldType()));
            esDataDTO.setConditionsEntityExtList(conditionsEntityExtList);
            PaasFormDataEsListVO esDataList = paasFormDataService.getEsDataList(esDataDTO);
            List<PaasFormDataEntityExt> supplierCommunicateESList = esDataList.getPaasFormDataESList();
            if (supplierCommunicateESList != null && !supplierCommunicateESList.isEmpty()) {
                JSONObject supplierCommunicateData = supplierCommunicateESList.get(0).getData();
                Long communicateTime = FastJsonHelper.getLongOrDefaultFromFormData(supplierCommunicateData, SupplierCommunicateEnum.COMMUNICATE_TIME.getAttr(), 0L);
                communicateTimeInterval = DateTimeUtil.getLastConnectTimeStr(communicateTime);
            }
            others.put("communicateTime", communicateTimeInterval);

            fillDataOthersAndSuperScript(supplierEntity,others,new JSONObject());
        }
    }

    @Override
    public PaasFormDataEsListVO getProductList(ProductListDataDTO productListDataDTO) throws XbbException {
        String barcode = productListDataDTO.getBarcode();
        if (Objects.isNull(barcode) || barcode.isEmpty()){
            throw new XbbException(ProductErrorCodeEnum.API_ERROR_205022);
        }
        List<ConditionsEntityExt> conditionsEntityExtList = productListDataDTO.getConditions();
        conditionsEntityExtList = Objects.isNull(conditionsEntityExtList) ? new ArrayList<>() : conditionsEntityExtList;
        conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.BARCODE.getAttr(),"",ProductEnum.BARCODE.getFieldType(),ConditionEnum.EQUAL.getSymbol(),Collections.singletonList(barcode)));
        productListDataDTO.setConditions(conditionsEntityExtList);
        return getProductListSuper(productListDataDTO);
    }

    @Override
    public PaasFormDataEsListVO getProductListSuper(ProductListDataDTO productListDataDTO) throws XbbException {
        Integer businessType = productListDataDTO.getBusinessType();
        Long distributorId = productListDataDTO.getDistributorId();
        String corpid = productListDataDTO.getCorpid();
        Integer distributorMark = productListDataDTO.getDistributorMark();
        if (Objects.equals(businessType, XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
            return priceSetService.getProductSearchList(productListDataDTO);
        }
        PaasFormEntityExt paasFormEntityExt;
        if (distributorMark == null && !Objects.equals(XbbRefTypeEnum.WORK_ORDER.getCode(), businessType)) {
            if (!Objects.equals(XbbRefTypeEnum.WORK_ORDER_V2.getCode(), businessType)){
                paasFormEntityExt = paasFormModel.getByKey(productListDataDTO.getFormId(), corpid);
                distributorMark = paasFormEntityExt.getDistributorMark();
            }
        }

        Long refId = productListDataDTO.getRefId();
        Integer refType = productListDataDTO.getRefType();
        List<Integer> sourceTypeList = Arrays.asList(XbbRefTypeEnum.REFUND.getCode(), XbbRefTypeEnum.RETURNED_PURCHASE.getCode(), XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode(), XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode(), XbbRefTypeEnum.PURCHASE_INSTOCK.getCode(), XbbRefTypeEnum.REFUND_INSTOCK.getCode(), XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode(),XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode(), XbbRefTypeEnum.OTHER_OUTSTOCK.getCode(), XbbRefTypeEnum.OTHER_INSTOCK.getCode(),XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode(), XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode());
        boolean isOld = true;
        List<ConditionsEntityExt> conditionsEntityExtList = productListDataDTO.getConditions() == null ? new ArrayList<>() : productListDataDTO.getConditions();
        List<BusinessProductEntity> sourceProductList = new ArrayList<>();
        SourceProductListVO sourceProductListVO = new SourceProductListVO();
        ProductFieldPojo stockField = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_STOCK, ProductEnum.STOCK.getAttr(), corpid);
        if (sourceTypeList.contains(businessType)) {
            // 是否是老数据
            if (BasicConstant.OLD_JXC){
                isOld = true;
            }else {
                isOld = relativeProductHelp.isOldData(corpid, refId, businessType, refType);
            }
            if (!isOld) {
                sourceProductListVO = relativeProductHelp.getSourceProductList(productListDataDTO);
                sourceProductList = sourceProductListVO.getBusinessProductList();
                List<Object> productIdList = new ArrayList<>();
                sourceProductList.forEach(item -> productIdList.add(item.getProductId()));
                if (productIdList.isEmpty()){
                    productIdList.add(-1L);
                }
                conditionsEntityExtList.add(new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(),"",FieldTypeEnum.DATAID.getType(),ConditionEnum.IN.getSymbol(),productIdList));
                productListDataDTO.setPage(1);
            }
        }

        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(productListDataDTO, formDataListDTO);
        formDataListDTO.setSimple(false);
        formDataListDTO.setSubBusinessType(XbbRefTypeEnum.SELECT_PRODUCT.getCode());
        conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.PARENT_ID.getAttr(),"",ProductEnum.PARENT_ID.getFieldType(), ConditionEnum.NOEQUAL.getSymbol(),Collections.singletonList(0)));
        List<List<ConditionsEntityExt>> shouldConditonList = formDataListDTO.getShouldConditions();
        saasListHelp.packageGroupList(formDataListDTO,conditionsEntityExtList,shouldConditonList);
        if (isOld) {
            saasListDataPermissionHelp.listDepAndUserDataPermission(shouldConditonList, productListDataDTO.getLoginUser(), XbbRefTypeEnum.PRODUCT.getCode(),formDataListDTO.getLoginUser().getDepSet());
        }

        List<Object> searchWarehouseIdList = productListDataDTO.getSearchWarehouseIdList();
        // 移动端仓库筛选
        if (CollectionUtils.isNotEmpty(searchWarehouseIdList)){
            conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.WAREHOUSE.getAttr(),"",ProductEnum.WAREHOUSE.getFieldType(),ConditionEnum.IN.getSymbol(),searchWarehouseIdList));
        }
        List<ConditionsEntityExt> conditions = productListDataDTO.getConditions();
        if (CollectionsUtil.isNotEmpty(conditions)) {
            Iterator<ConditionsEntityExt> iterator = conditions.iterator();
            while (iterator.hasNext()) {
                ConditionsEntityExt entityExt = iterator.next();
                if (entityExt.getAttr().equals(ProductEnum.WAREHOUSE.getAttr())) {
                    List<Object> value = entityExt.getValue();
                    // iterator.remove();  fix:53505 新建合同-选择关联产品，根据仓库筛选数据失败
                    searchWarehouseIdList = value;
                }else if (entityExt.getAttr().equals(ProductEnum.SPECIFICATION.getAttr())) {
                    entityExt.setAttr(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                }
                if (entityExt.getAttr().equals(ProductEnum.CATEGORY_ID.getAttr())) {
                    Long categoryId = Long.valueOf(entityExt.getValue().get(0).toString());
                    List<ProductCategoryEntity> productCategoryList = productCategoryService.getSubCategoryIdList(corpid, categoryId);
                    if (Objects.isNull(productCategoryList)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                    }
                    List<Long> productCategoryIdIn = new ArrayList<>();
                    productCategoryList.forEach(item->productCategoryIdIn.add(item.getId()));
                    if (!productCategoryIdIn.isEmpty()) {
                        List<Object> categoryIdIn = new ArrayList<>(productCategoryIdIn);
//                    EsConditionUtil.getConditionList(parentConditionList, ProductEnum.CATEGORY_ID.getAttr(), "",
//                            ProductEnum.CATEGORY_ID.getFieldType(), ConditionEnum.IN.getSymbol(), categoryIdIn);
                        entityExt.setSymbol(ConditionEnum.IN.getSymbol());
                        entityExt.setValue(categoryIdIn);
                    }
                }
            }
        }
        // 订货单，选择了经销商，只显示该经销商可采购商品中的产品
        if (Objects.nonNull(distributorId) && Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(), businessType) && DistributorMarkEnum.DISTRIBUTOR.getCode().equals(distributorMark)) {
            IndexTypeEnum indexTypeEnum = indexTypeModel.getCustomerIndex(corpid, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), SaasMarkEnum.SAAS.getCode());;
            PaasFormDataEntityExt paasEsModelByKey = paasEsModel.getByKey(distributorId, corpid, indexTypeEnum, null);
            JSONArray goodsIdArr = paasEsModelByKey.getData().getJSONArray(DistributorEnum.PURCHASEABLE_GOODS.getAttr());
            if (CollectionsUtil.isNotEmpty(goodsIdArr)) {
                ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                conditionsEntityExt.setAttr(ProductEnum.CATEGORY_ID.getAttr());
                conditionsEntityExt.setFieldType(ProductEnum.CATEGORY_ID.getFieldType());
                conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                conditionsEntityExt.setValue(goodsIdArr);
                conditionsEntityExtList.add(conditionsEntityExt);
            }
        }
        // 移动端还在用特殊筛选 不能去
        if (Objects.nonNull(productListDataDTO.getCategoryId())){
            List<ProductCategoryEntity> productCategoryList = productCategoryService.getSubCategoryIdList(corpid, productListDataDTO.getCategoryId());
            if (Objects.isNull(productCategoryList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            List<Long> productCategoryIdIn = new ArrayList<>();
            productCategoryList.forEach(item->productCategoryIdIn.add(item.getId()));
            if (!productCategoryIdIn.isEmpty()) {
                List<Object> categoryIdIn = new ArrayList<>(productCategoryIdIn);
//                    EsConditionUtil.getConditionList(parentConditionList, ProductEnum.CATEGORY_ID.getAttr(), "",
//                            ProductEnum.CATEGORY_ID.getFieldType(), ConditionEnum.IN.getSymbol(), categoryIdIn);
                conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.CATEGORY_ID.getAttr(),"",ProductEnum.CATEGORY_ID.getFieldType(),ConditionEnum.IN.getSymbol(),categoryIdIn));
            }
        }
        Map<Long,JSONObject> sourceMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (isOld) {
            sourceMap = productService.setProductConditionsSuper(productListDataDTO,conditionsEntityExtList, stockField);
//            conditionsEntityExtList.addAll(productService.setProductConditionsSuper(productListDataDTO));
        }
        formDataListDTO.setShouldConditions(shouldConditonList);
        formDataListDTO.setConditions(conditionsEntityExtList);
        formDataListDTO.setNameLike(productListDataDTO.getNameLike());
        // 固定编号排序
        Map<String, String> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        sortMap.put("sort", SortOrder.ASC.toString());
        sortMap.put("field", ProductEnum.SERIALNO.getAttr());
        formDataListDTO.setSortMap(sortMap);
        /*if (sourceTypeList.contains(businessType)) {
            List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias(), ProductEnum.NAME.getAttr(), FieldTypeEnum.SERIALNO.getAlias(), ProductEnum.SPECIFICATION.getAttr(),
                    ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), ProductEnum.COST.getAttr(), ProductEnum.PRICE.getAttr(), ProductEnum.PRODUCT_IMGS.getAttr(),
                    ProductEnum.STOCK.getAttr(), ProductEnum.UNIT.getAttr());
            formDataListDTO.setFieldList(fieldList);
        }*/
        PaasFormDataEsListVO formDataListVO;
        try {
            formDataListVO = formDataListSearchHelp.getEsListSuper(formDataListDTO);
            List<Long> productIdList = new ArrayList<>();
            Set<Long> multiUnitProductIdSet = new HashSet<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long, Long> unitMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (CollectionsUtil.isNotEmpty(formDataListVO.getPaasFormDataESList())){
                formDataListVO.getPaasFormDataESList().forEach(item -> {
                    productIdList.add(item.getDataId());
                    if (Objects.equals(item.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1)) {
                        multiUnitProductIdSet.add(item.getDataId());
                        unitMap.put(item.getDataId(), item.getData().getLong(ProductEnum.UNIT.getAttr()));
                    }
                });
                if (CollectionsUtil.isNotEmpty(searchWarehouseIdList)){
                    BoolQueryBuilder boolQueryBuilder = boolQuery();
                    boolQueryBuilder.filter(termQuery("corpid.keyword", formDataListDTO.getCorpid()));
                    boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
                    boolQueryBuilder.filter(termsQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.PRODUCT_ID), productIdList));
                    boolQueryBuilder.filter(termsQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_ID), searchWarehouseIdList));
                    boolQueryBuilder.filter(termQuery(ProductWarehouseSubFormEnum.getEsAttr(ProductWarehouseSubFormEnum.WAREHOUSE_CHECKED), 1));
                    List<PaasFormDataEntity> list = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT_WAREHOUSE, boolQueryBuilder, PaasFormDataEntity.class, Arrays.asList(ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.PRODUCT_ID), ProductWarehouseSubFormEnum.getAttrConnectData(ProductWarehouseSubFormEnum.NUM)));
                    List<ProductWarehouseEntity> productWarehouseEntities = transferSubFormHelper.transferFormDataToProductWarehouseList(list);
                    HashMap<Long, Double> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for (ProductWarehouseEntity entity : productWarehouseEntities) {
                        Double num = map.getOrDefault(entity.getProductId(),0D);
                        num = Arith.add(num, entity.getNum());
                        map.put(entity.getProductId(),num);
                    }
                    for (PaasFormDataEntityExt entityExt : formDataListVO.getPaasFormDataESList()){
                        entityExt.getData().put(ProductEnum.STOCK.getAttr(),map.getOrDefault(entityExt.getDataId(),0D));
                    }
                }
            }
            formDataListVO.getPaasFormDataESList().forEach(item -> {
                JSONObject originData = (JSONObject) CloneUtil.deepClone(item.getData());
                item.setOriginData(originData);
            });
            if (PlatFormEnum.WEB.getValue().equals(formDataListDTO.getPlatform())) {
//                formDataListSearchHelp.webDataAnalysis(formDataListDTO,formDataListVO);
                saasListHelp.analysisSaasDataList(formDataListVO, formDataListDTO.getExplainMap());
                formDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);
                if (formDataListDTO.getExplainMap().containsKey(ProductEnum.CATEGORY_ID.getAttr())){
                    saasListHelp.handleCategory(formDataListDTO, formDataListVO);
                }
                formDataListAnalysisDataHelp.analysisAmountOfThousandBits(formDataListVO, formDataListDTO.getAnalysisAmountOfThousandBitsWithOriginalValue());
            } else if (PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform())) {
                formDataListVO = formDataListSearchHelp.appDataAnalysis(formDataListDTO, formDataListVO);
            }

            if (Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode())) {
                Map<String, FieldAttrEntity> explainMap = formDataListVO.getExplainMap();
                boolean inVisible = !explainMap.containsKey(ProductEnum.COST.getAttr()) || explainMap.get(ProductEnum.COST.getAttr()).getVisible() == 0 || explainMap.get(ProductEnum.COST.getAttr()).getIsOpen() == 0;
                List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataESList) {
                    JSONObject productData = paasFormDataEntityExt.getData();
                    JSONObject sourceData = paasFormDataEntityExt.getSourceData();
                    if (!productData.containsKey(ProductEnum.COST.getAttr()) || Objects.isNull(productData.get(ProductEnum.COST.getAttr())) || inVisible) {
                        sourceData.put(ProductEnum.COST.getAttr(), 0);
                    }
                }
            }

            productService.setChildSpecification(formDataListVO.getPaasFormDataESList(),formDataListDTO.getCorpid());
            LinkProductRelyEntity linkProductRelyEntity = null;
            if (Objects.nonNull(productListDataDTO.getSourceFormId())) {
                Long sourceFormId = productListDataDTO.getSourceFormId();
                linkProductRelyEntity = linkProductRelyModel.getByAttrAndFormIdAndLinkFormId(corpid, productListDataDTO.getAttr(), productListDataDTO.getFormId(), sourceFormId, DelEnum.NORMAL.getDel());
            } else {
                if (Objects.nonNull(productListDataDTO.getSourceBusinessType())) {
                    linkProductRelyEntity = linkProductRelyModel.getByAttrAndFormIdAndSourceBusinessType(corpid, productListDataDTO.getAttr(), productListDataDTO.getFormId(), productListDataDTO.getSourceBusinessType(), DelEnum.NORMAL.getDel());
                } else {
                    List<LinkProductRelyEnum> linkProductRelyEnumList = LinkProductRelyEnum.getByBuinessType(businessType);
                    if (!linkProductRelyEnumList.isEmpty()) {
                        linkProductRelyEntity = linkProductRelyModel.getByAttrAndFormIdAndSourceBusinessType(corpid, productListDataDTO.getAttr(), productListDataDTO.getFormId(), linkProductRelyEnumList.get(0).getSourceBusinessType(), DelEnum.NORMAL.getDel());
                    }
                }
            }
             // 源单解释
            Map<String, FieldAttrEntity> sourceExplainMap = null;
            // 当前表单解释
            Map<String, FieldAttrEntity> thisExplainMap = null;
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(productListDataDTO, userAndDepartmentGetDTO);
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            // 当前表单某个关联产品解释
            Map<String, FieldAttrEntity> subThisExplainMap = null;
            // 源单某个关联产品解释
            Map<String, FieldAttrEntity> subSourceExplainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            // 当前表单某个关联产品子字段与源单某个关联产品对应关系
            Map<String, String> thisToTarget = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            if (Objects.nonNull(linkProductRelyEntity)) {
                // 源数据表单
                PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, linkProductRelyEntity.getSourceFormId(), linkProductRelyEntity.getSourceBusinessType());
                List<FieldAttrEntity>  explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                sourceExplainMap = ExplainUtil.getExplainMapByList(explainList, null);
                // 当前表单解释
                PaasFormExplainEntity displayFormExplain = proFormHelp.getExplainEntity(corpid, linkProductRelyEntity.getFormId(), linkProductRelyEntity.getBusinessType());
                thisExplainMap = ExplainUtil.getExplainMap(displayFormExplain.getExplains(), null);
                subThisExplainMap = businessProductService.getProductRelyMap(linkProductRelyEntity.getField(), linkProductRelyEntity, sourceExplainMap, thisExplainMap, subSourceExplainMap, thisToTarget);
            }
            Map<Long, MultiUnitItemPoJo> groupBaseUnitMap = relativeProductHelp.getGroupBaseUnitMap(corpid);
            if (!isOld) {
                Map<Long, PaasFormDataEntityExt>  paasFormDataMap = new HashMap<>(formDataListVO.getPaasFormDataESList().size());
                formDataListVO.getPaasFormDataESList().forEach(item -> paasFormDataMap.put(item.getDataId(), item));
                formDataListVO.setPageHelper(sourceProductListVO.getPageHelper());
                List<PaasFormDataEntityExt>  paasFormDataList = new ArrayList<>();
                List<String> batchs = new ArrayList<>();
                Long warehouseId = 0L;
                HashSet<Long> productIds = new HashSet<>();
                Map<Long, Double> productRate = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                for (BusinessProductEntity item : sourceProductList){
                    Long productId = item.getProductId();
                    productIds.add(productId);
                    warehouseId = item.getWarehouseId();
                    productRate.put(item.getId(), Objects.isNull(item.getRate()) ? 1D : item.getRate());
                    if (paasFormDataMap.containsKey(productId)) {
                        // 遇到fastJson：default constructor not found问题用fastJson方法替代CloneUtil.deepClone实现深克隆 edit by kaka
                        PaasFormDataEntityExt paasFormDataEntityExt = JSON.parseObject(JSON.toJSONString(paasFormDataMap.get(productId)), PaasFormDataEntityExt.class);
                        paasFormDataEntityExt.setRefProductId(item.getId());
                        relativeProductHelp.putProductSourceData(paasFormDataEntityExt.getData(), paasFormDataEntityExt.getSourceData(), item, businessType, corpid, stockField);
                        paasFormDataEntityExt.setId(item.getId());
                        paasFormDataEntityExt.getData().put(SelectProductEnum.SOURCE_DOC.getAttr(), item.getSheetNo());
                        if (Objects.nonNull(item.getProduceDate())){
                            paasFormDataEntityExt.getData().put(SelectProductEnum.SOURCE_PRODUCE_DATE.getAttr(),DateUtil.getDateString(item.getProduceDate().intValue()));
                        }
                        if (!StringUtil.isEmpty(item.getBatch())){
                            batchs.add(item.getBatch());
                        }
                        paasFormDataEntityExt.getSourceData().put(SelectProductEnum.SOURCE_DOC.getAttr(), item.getSheetNo());
                        if (!thisToTarget.isEmpty()) {
                            JSONObject productBusinessData = item.getData();
                            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                            BeanUtil.copyProperties(productListDataDTO, parseSingleRowDataDTO);
                            parseSingleRowDataDTO.setDataJsonObject(productBusinessData);
                            parseSingleRowDataDTO.setUserMap(userMap);
                            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                            parseSingleRowDataDTO.setExplainMap(subSourceExplainMap);
                            ParseSingleRowDataVO parseSingleRowDataVO = formDataUpdateGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
                            if(Objects.isNull(parseSingleRowDataVO)){
                                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                            }
                            JSONObject result = parseSingleRowDataVO.getResult();
                            JSONObject thisData = businessProductService.formatThisFormData(subThisExplainMap, thisToTarget, result);
                            paasFormDataEntityExt.getData().getJSONObject(BusinessConstant.SOURCE_INFO).putAll(thisData);
                            paasFormDataEntityExt.getSourceData().getJSONObject(BusinessConstant.SOURCE_INFO).putAll(thisData);
                        }
                        paasFormDataList.add(paasFormDataEntityExt);
                    }
                }
                formDataListVO.setPaasFormDataESList(paasFormDataList);


                if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode())
                        || Objects.equals(refType, InstockTypeEnum.TRANSFER_INSTOCK.getCode())
                        || Objects.equals(refType, InstockTypeEnum.INVENTORY_INSTOCK.getCode())
                        || Objects.equals(businessType, XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode())
                        || Objects.equals(refType, OutstockTypeEnum.TRANSFER_OUTSTOCK.getCode())
                        || Objects.equals(refType, OutstockTypeEnum.INVENTORY_OUTSTOCK.getCode())) {
                    ProductFieldPojo costField = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_COST,ProductEnum.COST.getAttr(), corpid);
                    Integer accuracy = costField.getAccuracy();
                    Map<String, Double> productNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Map<String, Double> productCostMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    params.put("del", DelEnum.NORMAL.getDel());
                    params.put(ParameterConstant.CORPID, corpid);
                    params.put("productIdIn", productIds);
                    params.put("warehouseId", warehouseId);
                    List<ProductWarehouseEntity> entitys = productWarehouseModel.findEntitysWithWarehouseChecked(params, 1);
                    entitys.forEach(item ->{
                        productNumMap.put(item.getWarehouseKey(), item.getNum());
                        productCostMap.put(item.getWarehouseKey(), attrDecimalPrecisionHelper.setPrecision(item.getCost(),accuracy));
                    });
                    //源单产品有批次单取批次成本和批次库存
                    if (!batchs.isEmpty()) {
                        params.clear();
                        params.put("del", DelEnum.NORMAL.getDel());
                        params.put(ParameterConstant.CORPID, corpid);
                        params.put("productIdIn", productIds);
                        params.put("warehouseId", warehouseId);
                        params.put("batchIn", batchs);
                        List<ProductStockEntity> productStockEntities = productStockModel.findEntitys(params);
                        productStockEntities.forEach(item -> {
                            productNumMap.put(item.getBatchKey(), item.getNum());
                            productCostMap.put(item.getBatchKey(), attrDecimalPrecisionHelper.setPrecision(item.getCost(),accuracy));
                        });
                    }
                    for (PaasFormDataEntityExt entityExt : paasFormDataList) {
                        JSONObject data = entityExt.getData();
                        JSONObject sourceInfo = data.getJSONObject(BusinessConstant.SOURCE_INFO);
                        String key;
                        if (StringUtil.isNotEmpty(sourceInfo.getString(SelectProductEnum.BATCH.getAttr()))) {
                            String batch = sourceInfo.getString(SelectProductEnum.BATCH.getAttr());
                            if (sourceInfo.get(SelectProductEnum.BATCH.getAttr()) instanceof Map){
                                batch = sourceInfo.getJSONObject(SelectProductEnum.BATCH.getAttr()).getString("value");
                            }
                            key = formDataValidateProductHelp.getBatchKey(entityExt.getDataId(), warehouseId, batch, sourceInfo.getLong(SelectProductEnum.PRODUCE_DATE.getAttr()), FastJsonHelper.getLongOrDefaultFromFormData(sourceInfo, SelectProductEnum.GUARANTEE_PERIOD.getAttr(), 0L) * TimeConstant.SECONDS_PER_DAY);
                        }else {
                            key = entityExt.getDataId() + "_" + warehouseId;
                        }
                        sourceInfo.put(SelectProductEnum.STOCK.getAttr(), productNumMap.getOrDefault(key, 0D));
                        if (!(Objects.equals(refType, InstockTypeEnum.TRANSFER_INSTOCK.getCode()) && Objects.equals(businessType, XbbRefTypeEnum.OTHER_INSTOCK.getCode()))) {
                            sourceInfo.put(SelectProductEnum.COST.getAttr(), Arith.mul(productRate.getOrDefault(entityExt.getId(), 1D), productCostMap.getOrDefault(key, 0D)));
                        }
                    }
                }
            }else {

                JSONObject multiUnitItem;
                for (PaasFormDataEntityExt entityExt : formDataListVO.getPaasFormDataESList()) {
                    if (Objects.equals(entityExt.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1)) {
                        MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.getOrDefault(unitMap.get(entityExt.getDataId()), new MultiUnitItemPoJo());
                        multiUnitItem = new JSONObject();
                        multiUnitItem.put(MultiUnitConstant.MULTI_UNIT_TEXT, multiUnitItemPoJo.getBaseName());
                        multiUnitItem.put(MultiUnitConstant.VALUE, multiUnitItemPoJo.getBaseValue());
                        entityExt.getSourceData().put(ProductEnum.UNIT.getAttr(), multiUnitItem);
                    }
                    JSONObject sourceInfo = sourceMap.getOrDefault(entityExt.getDataId(),new JSONObject());
                    if (sourceTypeList.contains(businessType) || Objects.equals(XbbRefTypeEnum.OTHER_OUTSTOCK.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.OTHER_INSTOCK.getCode(), businessType)
                        || Objects.equals(XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode(), businessType)) {
                        sourceInfo.putIfAbsent(SelectProductEnum.COST.getAttr(),entityExt.getData().getDouble(ProductEnum.COST.getAttr()));
                        sourceInfo.putIfAbsent(SelectProductEnum.STOCK.getAttr(),entityExt.getData().getDouble(ProductEnum.STOCK.getAttr()));
                        sourceInfo.put(SelectProductEnum.UNIT.getAttr(),entityExt.getSourceData().get(ProductEnum.UNIT.getAttr()));
                        entityExt.getData().put(BusinessConstant.SOURCE_INFO, sourceInfo);
                        entityExt.getSourceData().put(BusinessConstant.SOURCE_INFO, sourceInfo);
                    }
                    if (Objects.equals(businessType,XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())){
                        JSONObject data = entityExt.getData();
                        if (Objects.nonNull(data)) {
                            data.put(SelectProductEnum.SOURCE_PRICE.getAttr(),sourceInfo.get(SelectProductEnum.SELLING_PRICE.getAttr()));
                        }
                    } else if (Objects.equals(businessType,XbbRefTypeEnum.REFUND.getCode())){
                        JSONObject data = entityExt.getData();
                        if (Objects.nonNull(data)) {
                            data.put(SelectProductEnum.SOURCE_PRICE.getAttr(),sourceInfo.get(SelectProductEnum.PRICE.getAttr()));
                        }
                    }
                    if (!thisToTarget.isEmpty()) {
                        JSONObject productBusinessData = sourceInfo.getJSONObject(BusinessConstant.RELATION_PRODUCT_DATA);
                        if (Objects.nonNull(productBusinessData)) {
                            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                            BeanUtil.copyProperties(productListDataDTO, parseSingleRowDataDTO);
                            parseSingleRowDataDTO.setDataJsonObject(productBusinessData);
                            parseSingleRowDataDTO.setUserMap(userMap);
                            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                            parseSingleRowDataDTO.setExplainMap(subSourceExplainMap);
                            ParseSingleRowDataVO parseSingleRowDataVO = formDataUpdateGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
                            if(Objects.isNull(parseSingleRowDataVO)){
                                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                            }
                            JSONObject result = parseSingleRowDataVO.getResult();
                            JSONObject thisData = businessProductService.formatThisFormData(subThisExplainMap, thisToTarget, result);
                            entityExt.getData().getJSONObject(BusinessConstant.SOURCE_INFO).putAll(thisData);
                            entityExt.getSourceData().getJSONObject(BusinessConstant.SOURCE_INFO).putAll(thisData);
                        }
                    }
                }
            }
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            /**
             *选择产品封装回参
             */
            boolean noNeedWarehouse = Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode())
                        || Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.PURCHASE.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.RETURNED_PURCHASE.getCode())
                        || Objects.equals(businessType, XbbRefTypeEnum.BOM_BILL.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER_V2.getCode());
            if (CollectionsUtil.isNotEmpty(formDataListVO.getPaasFormDataESList()) && !noNeedWarehouse){
                Map<Long,Map<String,JSONObject>> productMap = formDataValidateProductHelp.getWarehouseMap(productIdList,productListDataDTO.getCorpid());
                // 特殊逻辑 如果有问题直接来找我
                List<PaasFormDataEntityExt> paasFormDataEntityExtList = formDataListVO.getPaasFormDataESList();
                switch(xbbRefTypeEnum){
                    case RETURNED_MATERIEL_INSTOCK:
                        for(int i = 0;i < paasFormDataEntityExtList.size(); i++){
                            Long productId = paasFormDataEntityExtList.get(i).getDataId();
                            JSONObject sourceData = paasFormDataEntityExtList.get(i).getSourceData();
                            Map<String,JSONObject> value = productMap.getOrDefault(productId,new HashMap<>());
                            Collection<JSONObject> values = value.values();
                            values.forEach(item->item.put("cost",sourceData.getDoubleValue(SelectProductEnum.COST.getAttr())));
                        }
                        break;
                    case OTHER_INSTOCK:
                        for(int i = 0;i < paasFormDataEntityExtList.size(); i++){
                            JSONObject data = paasFormDataEntityExtList.get(i).getData();
                            JSONObject sourceInfo = data.getJSONObject(BusinessConstant.SOURCE_INFO);
                            data.put(SelectProductEnum.SOURCE_MEMO.getAttr(), sourceInfo.getString(InstockProductEnum.MEMO.getAttr()));
                            data.put(SelectProductEnum.SOURCE_BATCH.getAttr(), sourceInfo.getString(InstockProductEnum.BATCH.getAttr()));
                            data.put(SelectProductEnum.SOURCE_PRODUCE_DATE.getAttr(), sourceInfo.getLong(InstockProductEnum.PRODUCE_DATE.getAttr()));
                            data.put(SelectProductEnum.SOURCE_GUARANTEE_PERIOD.getAttr(), sourceInfo.getLong(InstockProductEnum.GUARANTEE_PERIOD.getAttr()));
                        }
                        break;
                    case OTHER_OUTSTOCK:
                        for(int i = 0;i < paasFormDataEntityExtList.size(); i++){
                            JSONObject data = paasFormDataEntityExtList.get(i).getData();
                            JSONObject sourceInfo = data.getJSONObject(BusinessConstant.SOURCE_INFO);
                            data.put(SelectProductEnum.SOURCE_MEMO.getAttr(), sourceInfo.getString(OutstockProductEnum.MEMO.getAttr()));
                            data.put(SelectProductEnum.SOURCE_BATCH.getAttr(), Objects.nonNull(sourceInfo.getJSONObject(OutstockProductEnum.BATCH.getAttr())) ? sourceInfo.getJSONObject(OutstockProductEnum.BATCH.getAttr()).getString("text") : "");
                            data.put(SelectProductEnum.SOURCE_PRODUCE_DATE.getAttr(), sourceInfo.getLong(OutstockProductEnum.PRODUCE_DATE.getAttr()));
                            data.put(SelectProductEnum.SOURCE_GUARANTEE_PERIOD.getAttr(), sourceInfo.getLong(OutstockProductEnum.GUARANTEE_PERIOD.getAttr()));
                        }
                        break;
                    case WORK_ORDER_OUTSTOCK:
                        for(int i = 0;i < paasFormDataEntityExtList.size(); i++){
                            JSONObject data = paasFormDataEntityExtList.get(i).getData();
                            JSONObject sourceInfo = data.getJSONObject(BusinessConstant.SOURCE_INFO);
                            data.put(SelectProductEnum.SOURCE_PRICE.getAttr(), sourceInfo.getString(SelectProductEnum.PRICE.getAttr()));
                        }
                        break;
                    case INVENTORY:
                        inventoryService.filterBatchStock(productMap, productIdList, corpid);
                        break;
                    default:
                        break;
                }
                for (PaasFormDataEntityExt entityExt : formDataListVO.getPaasFormDataESList()){
                    if (productMap.containsKey(entityExt.getDataId())){
                        entityExt.getSourceData().put("warehouse",productMap.get(entityExt.getDataId()));
                    }else {
                        entityExt.getSourceData().put("warehouse",new JSONObject());
                    }
                    if (Objects.isNull(entityExt.getData().getLong(SelectProductEnum.SOURCE_PRODUCE_DATE.getAttr())) || Objects.equals(entityExt.getData().getLong(SelectProductEnum.SOURCE_PRODUCE_DATE.getAttr()), 0L)) {
                        entityExt.getData().remove(SelectProductEnum.SOURCE_GUARANTEE_PERIOD.getAttr());
                    }
                }
            }
            // 进销存是否开启
            Boolean isJxcUse = paasAppService.validateAppEnable(null, XbbRefTypeEnum.JXC.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
            // 批次序列号开关 多单位
            Map<Long, List<MultiUnitPricePoJo>> priceMap = new HashMap<>(1 << 1);
            if (StockConstant.MULTI_UNIT_PRICE_TYPE_LIST.contains(businessType)) {
                priceMap = productUnitPriceModel.getPriceMapByProductIdSet(corpid, multiUnitProductIdSet);
            }
            Map<Long, List<UnitItemPoJo>> groupItemsMap = relativeProductHelp.getGroupItemsMap(corpid);
            for (PaasFormDataEntityExt entityExt : formDataListVO.getPaasFormDataESList()){
               JSONObject extData = entityExt.getData();
               JSONObject extSourceData = entityExt.getSourceData();
               JSONObject sellingMap = new JSONObject();
               Integer enableMultiUnit = getIntegerOrDefaultFromFormData(extData, ProductEnum.ENABLE_MULTI_UNIT.getAttr(), 0);
               Integer enableSerial = getIntegerOrDefaultFromFormData(extData, ProductEnum.ENABLE_SERIAL_NUMBER.getAttr(), 0);
               if (Objects.nonNull(extData) && CollectionsUtil.isEmpty(extData.getJSONArray(ProductEnum.PRODUCT_IMGS.getAttr()))) {
                    extData.put(ProductEnum.PRODUCT_IMGS.getAttr(), extData.getJSONArray(ProductEnum.THUMBNAIL.getAttr()));
                    extSourceData.put(ProductEnum.PRODUCT_IMGS.getAttr(), extSourceData.getJSONArray(ProductEnum.THUMBNAIL.getAttr()));
               }
               // 是多单位产品且不是开启序列号产品
               if (Objects.equals(enableMultiUnit, 1)) {
                   List<UnitItemPoJo> unitItemPoJos = groupItemsMap.get(unitMap.getOrDefault(entityExt.getDataId(), 0L));
                   MultiUnitItemPoJo multiUnitItemPoJo = groupBaseUnitMap.get(unitMap.getOrDefault(entityExt.getDataId(), 0L));
                   if (!isOld) {
                       JSONObject unitJSON = extData.getJSONObject(ProductEnum.UNIT.getAttr());
                       List<UnitItemPoJo> copyUnitItem = (List<UnitItemPoJo>) CloneUtil.deepClone(unitItemPoJos);
                       if (Objects.isNull(unitJSON) || !(unitJSON.get(MultiUnitConstant.VALUE) instanceof Number && unitJSON.getLong(MultiUnitConstant.VALUE) > ProductConstant.MAX_SINGLE_UNIT_VALUE)) {
                           copyUnitItem.removeIf(unitItemPoJo -> !Objects.equals(unitItemPoJo.getIsBase(), 1));
                           JSONObject sourceInfo = extData.getJSONObject(BusinessConstant.SOURCE_INFO);
                           if (Objects.nonNull(multiUnitItemPoJo)) {
                               JSONObject baseUnitObj = new JSONObject();
                               baseUnitObj.put(MultiUnitConstant.MULTI_UNIT_TEXT, multiUnitItemPoJo.getBaseName());
                               baseUnitObj.put(MultiUnitConstant.VALUE, multiUnitItemPoJo.getBaseValue());
                               sourceInfo.put(ProductEnum.UNIT.getAttr(), baseUnitObj);
                           }
                       } else {
                           copyUnitItem.removeIf(unitItemPoJo -> !Objects.equals(unitItemPoJo.getIsBase(), 1) && !Objects.equals(unitJSON.getLongValue(MultiUnitConstant.VALUE), unitItemPoJo.getValue()));
                       }
                       extSourceData.put(ProductConstant.UNIT_RATE, copyUnitItem);
                   } else {
                       extSourceData.put(ProductConstant.UNIT_RATE, unitItemPoJos);
                   }
                   extSourceData.put(ProductConstant.TRANSFORM_UNIT_RATE, unitItemPoJos);
                   // 多单位业务且非序列号业务且未启用序列号
                   if (StockConstant.MULTI_UNIT_TYPE_LIST.contains(businessType) && !(StockConstant.SERIAL_TYPE_LIST.contains(businessType) && Objects.equals(enableSerial, 1))) {
                       extSourceData.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), 1);
                       if (StockConstant.MULTI_UNIT_PRICE_TYPE_LIST.contains(businessType)) {
                           extSourceData.put(ProductConstant.PRICE, priceMap.get(entityExt.getDataId()));
                       }
                       JSONObject sellingData;
                       if (extSourceData.containsKey(BusinessConstant.SOURCE_INFO)) {
                           sellingData = extSourceData.getJSONObject(BusinessConstant.SOURCE_INFO);
                       } else {
                           sellingData = extSourceData;
                       }
                       sellingMap.put(SelectProductEnum.UNIT.getAttr(), sellingData.get(SelectProductEnum.UNIT.getAttr()));
                       switch (xbbRefTypeEnum) {
                           case PURCHASE:
                               sellingMap.put(SelectProductEnum.PRICE.getAttr(), sellingData.get(ProductEnum.COST.getAttr()));
                               break;
                           case CONTRACT:
                           case SALES_OPPORTUNITY:
                           case QUOTATION:
                               sellingMap.put(SelectProductEnum.SELLING_PRICE.getAttr(), sellingData.get(ProductEnum.PRICE.getAttr()));
                               break;
                           default:
                               sellingData.forEach((key,value)->{
                                   if (ProductConstant.MULTI_PRICE_ATTR_LIST.contains(key)) {
                                       sellingMap.put(key, value);
                                   }
                               });
                               break;
                       }
                       extSourceData.put(ProductConstant.SELLING_PRICE_MAP, sellingMap);
                   } else {
                       extSourceData.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), 0);
                   }
               } else {
                   extSourceData.put(ProductEnum.ENABLE_MULTI_UNIT.getSaasAttr(), 0);
               }
               if (StockConstant.BATCH_TYPE_LIST.contains(businessType)) {
                    // 进销存为启用时，退货退款不可选序列号
                    if (isJxcUse) {
                        extData.put(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr(), extData.getLongValue(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr()));
                        extSourceData.put(ProductEnum.ENABLE_SERIAL_NUMBER.getSaasAttr(), extData.getLongValue(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr()));
                        if (BasicConstant.ONE.equals(extData.getInteger(ProductEnum.ENABLE_SERIAL_NUMBER.getAttr()))) {
                            extData.put(SelectProductEnum.NUM.getAttr(), null);
                            extSourceData.put(SelectProductEnum.NUM.getAttr(), null);
                        }
                    }
                    Integer enableBatch = getIntegerOrDefaultFromFormData(extData, ProductEnum.ENABLE_BATCH_SHELF_LIFE.getAttr(), 0);
                    extData.put(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getSaasAttr(), enableBatch);
                    extSourceData.put(ProductEnum.ENABLE_BATCH_SHELF_LIFE.getSaasAttr(), enableBatch);
                    if (Objects.equals(enableBatch,EnableEnum.CLOSE.getCode())) {
                        extData.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), EnableEnum.CLOSE.getCode());
                        extSourceData.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), EnableEnum.CLOSE.getCode());
                        extData.remove(SelectProductEnum.SOURCE_BATCH.getAttr());
                        extData.remove(SelectProductEnum.SOURCE_PRODUCE_DATE.getAttr());
                        extData.remove(SelectProductEnum.SOURCE_GUARANTEE_PERIOD.getAttr());
                        JSONObject sourceInfoExt = extSourceData.getJSONObject(BusinessConstant.SOURCE_INFO);
                        if (Objects.nonNull(sourceInfoExt)) {
                            sourceInfoExt.remove(SelectProductEnum.BATCH.getAttr());
                            sourceInfoExt.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
                            sourceInfoExt.remove(SelectProductEnum.PRODUCE_DATE.getAttr());
                            sourceInfoExt.remove(SelectProductEnum.EXPIRE_DATE.getAttr());
                        }
                    }else {
                        if (StringUtil.isEmpty(extData.getString(ProductEnum.SHELF_LIFE_DAYS.getAttr()))) {
                            extData.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), EnableEnum.CLOSE.getCode());
                            extSourceData.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), EnableEnum.CLOSE.getCode());
                            extData.remove(SelectProductEnum.SOURCE_PRODUCE_DATE.getAttr());
                            extData.remove(SelectProductEnum.SOURCE_GUARANTEE_PERIOD.getAttr());
                            JSONObject sourceInfoExt = extSourceData.getJSONObject(BusinessConstant.SOURCE_INFO);
                            if (Objects.nonNull(sourceInfoExt)) {
                                sourceInfoExt.remove(SelectProductEnum.GUARANTEE_PERIOD.getAttr());
                                sourceInfoExt.remove(SelectProductEnum.PRODUCE_DATE.getAttr());
                                sourceInfoExt.remove(SelectProductEnum.EXPIRE_DATE.getAttr());
                            }
                        }else {
                            extData.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), EnableEnum.OPEN.getCode());
                            extSourceData.put(ProductEnum.SHELF_LIFE_DAYS.getSaasAttr(), EnableEnum.OPEN.getCode());
                        }
                    }
                    if (Objects.isNull(extData.get(SelectProductEnum.SOURCE_PRODUCE_DATE.getAttr())) || Objects.equals(extData.getLong(SelectProductEnum.SOURCE_PRODUCE_DATE.getAttr()), 0L)) {
                        extData.remove(SelectProductEnum.SOURCE_GUARANTEE_PERIOD.getAttr());
                    }
                }
            }
            //没选经销商的暂时不处理
            if (Objects.nonNull(distributorId) && !formDataListVO.getPaasFormDataESList().isEmpty() && (Objects.equals(businessType, XbbRefTypeEnum.ORDER.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()))) {
                List<Long> productIdIn = new ArrayList<>();
                List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
                Map<Long, Boolean> multiUnitMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                paasFormDataESList.forEach(item -> {
                    productIdIn.add(item.getId());
                    multiUnitMap.put(item.getId(), Objects.equals(item.getData().getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1));
                });
                // 价目表
                Map<String, PriceProductSetEntity> productSetEntityMap = productModel.getPriceMap(corpid, distributorId, productListDataDTO.getFormId(), productIdIn, multiUnitMap);
                List<Long> priceIdList = new ArrayList<>();
                productSetEntityMap.forEach((k,v) ->{
                    priceIdList.add(v.getPriceId());
                });
                Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                param.put("corpid",corpid);
                param.put("del",DelEnum.NORMAL.getDel());
                param.put("idIn",priceIdList);
                List<PriceSetEntity> priceSetEntityList = priceSetModel.findEntitys(param);
                Map<Long, List<Integer>> scopeMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                priceSetEntityList.forEach(item ->{
                    List<Integer> scopeList = new ArrayList<>();
                    String scope = item.getScope().substring(item.getScope().indexOf("[") + 1, item.getScope().lastIndexOf("]"));
                    String [] scopeString = scope.split(",");
                    for(int i=0; i<scopeString.length; i++){
                        scopeList.add(Integer.valueOf(scopeString[i]));
                    }
                    scopeMap.put(item.getId(), scopeList);
                });
                // 促销活动,只有经销商有
                if (DistributorMarkEnum.DISTRIBUTOR.getCode().equals(distributorMark)) {
                    Map<Long, PromotionProductEntity> promotionMap = productHelp.getActivityList(corpid, distributorId, productIdIn);
                    paasFormDataESList.forEach(item -> {
                        Long productId = item.getId();
                        Double promotionDiscount = 1D;
                        Double price = 0D;
                        if (promotionMap.containsKey(productId)) {
                            promotionDiscount = Arith.div(promotionMap.get(productId).getDiscount(), 10D);
                        }
                        JSONObject sourceData = item.getSourceData();
                        boolean isMulti = Objects.equals(sourceData.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1);
                        if (isMulti) {
                            JSONArray priceArray = sourceData.getJSONArray(ProductConstant.PRICE);
                            for (int i = 0; i < priceArray.size(); i++) {
                                JSONObject priceObj = priceArray.getJSONObject(i);
                                String unitId = priceObj.getString("value");
                                String key = productId + SymbolConstant.UNDERLINE + unitId;
                                if (productSetEntityMap.containsKey(key)) {
                                    PriceProductSetEntity priceProductSetEntity = productSetEntityMap.get(key);
                                    Double sellingPrice = Arith.mul(priceProductSetEntity.getSellingPrice(), promotionDiscount);
                                    Double discount = Arith.mul(priceProductSetEntity.getDiscount(), promotionDiscount);
                                    priceObj.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), sellingPrice);
                                    priceObj.put(SelectProductEnum.DISCOUNT.getSaasAttr(), discount);
                                    priceArray.set(i, priceObj);
                                } else if (!Objects.equals(promotionDiscount, 1D)) {
                                    if (Objects.nonNull(priceObj) && Objects.nonNull(priceObj.getDouble("rate"))){
                                        price = priceObj.getDouble("rate");
                                    }
                                    priceObj.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), Arith.mul(price, promotionDiscount));
                                    priceObj.put(SelectProductEnum.DISCOUNT.getSaasAttr(), promotionDiscount);
                                    priceArray.set(i, priceObj);
                                }
                            }
                            sourceData.put(ProductConstant.PRICE, priceArray);
                            JSONObject sellingPriceMap = sourceData.getJSONObject(ProductConstant.SELLING_PRICE_MAP);
                            String key = productId + SymbolConstant.UNDERLINE + sellingPriceMap.getJSONObject(SelectProductEnum.UNIT.getAttr()).getString("value");
                            if (productSetEntityMap.containsKey(key)) {
                                PriceProductSetEntity priceProductSetEntity = productSetEntityMap.get(key);
                                Double sellingPrice = Arith.mul(priceProductSetEntity.getSellingPrice(), promotionDiscount);
                                Double discount = Arith.mul(priceProductSetEntity.getDiscount(), promotionDiscount);
                                sellingPriceMap.put(SelectProductEnum.SELLING_PRICE.getAttr(), sellingPrice);
                                sellingPriceMap.put(SelectProductEnum.DISCOUNT.getAttr(), discount);
                                sourceData.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), sellingPrice);
                            } else if (!Objects.equals(promotionDiscount, 1D)) {
                                if (Objects.nonNull(sellingPriceMap) && Objects.nonNull(sellingPriceMap.getDouble(SelectProductEnum.SELLING_PRICE.getAttr()))){
                                    price = sellingPriceMap.getDouble(SelectProductEnum.SELLING_PRICE.getAttr());
                                }
                                sellingPriceMap.put(SelectProductEnum.SELLING_PRICE.getAttr(), Arith.mul(price, promotionDiscount));
                                sellingPriceMap.put(SelectProductEnum.DISCOUNT.getAttr(), Arith.mul(promotionDiscount, 100D));
                                sourceData.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), Arith.mul(price, promotionDiscount));
                            }
                        } else {
                            String key = productId.toString();
                            if (productSetEntityMap.containsKey(key)) {
                                PriceProductSetEntity priceProductSetEntity = productSetEntityMap.get(key);
                                Double sellingPrice = Arith.mul(priceProductSetEntity.getSellingPrice(), promotionDiscount);
                                Double discount = Arith.mul(priceProductSetEntity.getDiscount(), promotionDiscount);
                                sourceData.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), sellingPrice);
                                sourceData.put(SelectProductEnum.DISCOUNT.getSaasAttr(), discount);
                            }else if (!Objects.equals(promotionDiscount, 1D)) {
                                if (Objects.nonNull(sourceData) && Objects.nonNull(sourceData.getDouble(SelectProductEnum.PRICE.getAttr()))){
                                    price = sourceData.getDouble(SelectProductEnum.PRICE.getAttr());
                                }
                                sourceData.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), Arith.mul(price , promotionDiscount));
                                sourceData.put(SelectProductEnum.DISCOUNT.getSaasAttr(), promotionDiscount);
                            }
                        }
                    });
                } else if (Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.QUOTATION.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
                    paasFormDataESList.forEach(item -> {
                        Long productId = item.getId();
                        JSONObject sourceData = item.getSourceData();
                        Double price = null;
                        Double discount = 1D;
                        boolean isMulti = Objects.equals(sourceData.getInteger(ProductEnum.ENABLE_MULTI_UNIT.getAttr()), 1);
                        if (isMulti) {
                            JSONArray priceArray = sourceData.getJSONArray(ProductConstant.PRICE);
                            Double subPrice = null;
                            Double subDiscount = 1D;
                            if (CollectionsUtil.isNotEmpty(priceArray)) {
                                for (int i = 0; i < priceArray.size(); i++) {
                                    JSONObject priceObj = priceArray.getJSONObject(i);
                                    String unitId = priceObj.getString("value");
                                    String key = productId + SymbolConstant.UNDERLINE + unitId;
                                    boolean scope = false;
                                    if (productSetEntityMap.containsKey(key)) {
                                        PriceProductSetEntity priceProductSetEntity = productSetEntityMap.get(key);
                                        List<Integer> scopeList = scopeMap.get(priceProductSetEntity.getPriceId());
                                        scope = PriceSetScopeEnum.getBusinessTypeByType(businessType, scopeList);
                                    }
                                    if (scope) {
                                        PriceProductSetEntity priceProductSetEntity = productSetEntityMap.get(key);
                                        subPrice = priceProductSetEntity.getSellingPrice();
                                        subDiscount = priceProductSetEntity.getDiscount();
                                    } else if (!Objects.equals(discount, 1D)) {
                                        if (Objects.nonNull(priceObj) && Objects.nonNull(priceObj.getDouble("rate"))) {
                                            subPrice = priceObj.getDouble("rate");
                                        }
                                        if (Objects.nonNull(priceObj) && Objects.nonNull(priceObj.getDouble(SelectProductEnum.DISCOUNT.getAttr()))) {
                                            subDiscount = priceObj.getDouble(SelectProductEnum.DISCOUNT.getAttr());
                                        }
                                        if (Objects.nonNull(subPrice)) {
                                            subPrice = Arith.mul(subPrice, subDiscount);
                                        }
                                    }
                                    // subPrice没有值（null）时前端才会计算售价
                                    priceObj.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), subPrice);
                                    priceObj.put(SelectProductEnum.DISCOUNT.getSaasAttr(), subDiscount);
                                    priceArray.set(i, priceObj);
                                }
                            }
                            sourceData.put(ProductConstant.PRICE, priceArray);
                            JSONObject sellingPriceMap = sourceData.getJSONObject(ProductConstant.SELLING_PRICE_MAP);
                            String key = productId + SymbolConstant.UNDERLINE + sellingPriceMap.getJSONObject(SelectProductEnum.UNIT.getAttr()).getString("value");
                            boolean scope = false;
                            if (productSetEntityMap.containsKey(key)) {
                                PriceProductSetEntity priceProductSetEntity = productSetEntityMap.get(key);
                                List<Integer> scopeList = scopeMap.get(priceProductSetEntity.getPriceId());
                                scope = PriceSetScopeEnum.getBusinessTypeByType(businessType, scopeList);
                            }
                            if (scope) {
                                PriceProductSetEntity priceProductSetEntity = productSetEntityMap.get(key);
                                Double sellingPrice = Arith.mul(priceProductSetEntity.getSellingPrice(), discount);
                                discount = Arith.mul(priceProductSetEntity.getDiscount(), discount);
                                sellingPriceMap.put(SelectProductEnum.SELLING_PRICE.getAttr(), sellingPrice);
                                sellingPriceMap.put(SelectProductEnum.DISCOUNT.getAttr(), discount);
                                sourceData.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), sellingPrice);
                            } else if (!Objects.equals(discount, 1D)) {
                                if (Objects.nonNull(sellingPriceMap) && Objects.nonNull(sellingPriceMap.getDouble(SelectProductEnum.SELLING_PRICE.getAttr()))){
                                    price = sellingPriceMap.getDouble(SelectProductEnum.SELLING_PRICE.getAttr());
                                }
                                if (Objects.nonNull(sellingPriceMap) && Objects.nonNull(sellingPriceMap.getDouble(SelectProductEnum.DISCOUNT.getAttr()))) {
                                    discount = sellingPriceMap.getDouble(SelectProductEnum.DISCOUNT.getAttr());
                                }
                                if (Objects.nonNull(price)) {
                                    price = Arith.mul(price, discount);
                                }
                                sellingPriceMap.put(SelectProductEnum.SELLING_PRICE.getAttr(), price);
                                sellingPriceMap.put(SelectProductEnum.DISCOUNT.getAttr(), discount);
                                sourceData.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), Arith.mul(price, discount));
                            }
                        } else {
                            String key = productId.toString();
                            boolean scope = false;
                            if (productSetEntityMap.containsKey(key)) {
                                PriceProductSetEntity priceProductSetEntity = productSetEntityMap.get(key);
                                List<Integer> scopeList = scopeMap.get(priceProductSetEntity.getPriceId());
                                scope = PriceSetScopeEnum.getBusinessTypeByType(businessType, scopeList);
                            }
                            if (scope) {
                                PriceProductSetEntity priceProductSetEntity = productSetEntityMap.get(key);
                                price = Arith.mul(priceProductSetEntity.getSellingPrice(), discount);
                                discount = Arith.mul(priceProductSetEntity.getDiscount(), discount);
                            }else if (!Objects.equals(discount, 1D)) {
                                if (Objects.nonNull(sourceData) && Objects.nonNull(sourceData.getDouble(SelectProductEnum.PRICE.getAttr()))){
                                    price = sourceData.getDouble(SelectProductEnum.PRICE.getAttr());
                                }
                                if (Objects.nonNull(sourceData) && Objects.nonNull(sourceData.getDouble(SelectProductEnum.DISCOUNT.getAttr()))) {
                                    discount = sourceData.getDouble(SelectProductEnum.DISCOUNT.getAttr());
                                }
                                if (Objects.nonNull(price)) {
                                    price = Arith.mul(price, discount);
                                }
                            }
                            sourceData.put(SelectProductEnum.SELLING_PRICE.getSaasAttr(), price);
                            sourceData.put(SelectProductEnum.DISCOUNT.getSaasAttr(), discount);
                        }
                    });
                }
            }
            // 开启了进销存的再做可用库存量的回显
            PaasAppEntity paasAppEntity = paasAppModel.getByAlias(XbbRefTypeEnum.JXC.getAlias(), corpid);
            boolean isOpenJxc = false;
            if (Objects.nonNull(paasAppEntity)) {
                isOpenJxc = paasAppEntity.getEnable() == 1;
            }
            if (isOpenJxc && !formDataListVO.getPaasFormDataESList().isEmpty() && Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
                //合同选择产品新增可用库存量
                List<FieldAttrEntity> fieldAttrEntities=formDataListVO.getHeadList().stream().filter(p ->Objects.equals(p.getAttr(),ProductEnum.STOCK.getAttr()) ).collect(Collectors.toList());
                if (!fieldAttrEntities.isEmpty()){
                    FieldAttrEntity stockAttr=fieldAttrEntities.get(0);
                    FieldAttrEntity availableStockAttr= (FieldAttrEntity) CloneUtil.deepClone(stockAttr);
                    availableStockAttr.setAttr("availableStock");
                    availableStockAttr.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.AVAILABLE_STOCK));
                    availableStockAttr.setEditable(1);
                    formDataListVO.getHeadList().add((formDataListVO.getHeadList().indexOf(stockAttr)+1),availableStockAttr);
                }
                //获取产品Id集合
                Map<Long, ContractProductEntity> contractProductEntityMap = new HashMap<>();
                //获取产品的待出库数量
                List<ContractProductEntity> waitOutProductEntitys = contractProductService.getWaitOutstockProductByProductIdIn(productIdList, corpid);
                if (CollectionsUtil.isNotEmpty(waitOutProductEntitys)) {
                    for (ContractProductEntity contractProductEntity : waitOutProductEntitys) {
                        contractProductEntityMap.put(contractProductEntity.getProductId(), contractProductEntity);
                    }
                }
                paasFormDataESList.forEach(item -> {
                    Long productId = item.getId();
                    //合同选择产品新增可用库存量
                    JSONObject productData = item.getData();
                    //设置可用库存量值
                    if (!contractProductEntityMap.isEmpty() && Objects.nonNull(contractProductEntityMap.get(productId))) {
                        if (Objects.nonNull(productData.getDouble(ProductEnum.STOCK.getAttr()))) {
                            productData.put("availableStock", Arith.sub(productData.getDouble(ProductEnum.STOCK.getAttr()), contractProductEntityMap.get(productId).getSumNum()));
                        } else {
                            productData.put("availableStock", "");
                        }
                    } else {
                        //如果没有待出库数量，可用库存量=库存
                        productData.put("availableStock", productData.get(ProductEnum.STOCK.getAttr()));
                    }
                });
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        formDataListVO.setExplainMap(new HashMap<>());
        // 选择产品弹窗关联新建产品
        Set<String> permSet = formDataListDTO.getLoginUser().getPermSet();
        if (permSet.contains(ListTopButtonEnum.PRODUCT_ADD.getProPermissionAlias())) {
            List<ButtonPojo> buttonList = new ArrayList<>();
            ButtonPojo buttonPojo = new ButtonPojo();
            buttonPojo.setAttr(SaasButtonEnum.ADD.getAttr());
            buttonPojo.setValue(SaasButtonEnum.ADD.getValue());
            buttonPojo.setType(SaasButtonEnum.ADD.getType());
            buttonList.add(buttonPojo);
            formDataListVO.setTopPermissions(buttonList);
        }
        return formDataListVO;
    }

    @Override
    public PaasFormDataEsListVO getProductSearchList(ProductListDataDTO productListDataDTO) throws XbbException {
        String corpid = productListDataDTO.getCorpid();
        Long formId = productListDataDTO.getFormId();
        List<ConditionsEntityExt> conditionsEntityExtList = productListDataDTO.getConditions() == null ? new ArrayList<>() : productListDataDTO.getConditions();
        //解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        PaasFormEntityExt paasFormEntityExt;
        if (Objects.equals(productListDataDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER_V2.getCode())) {
            if (Objects.isNull(formId) || Objects.equals(formId, 0L)) {
                formId = paasFormExplainEntity.getFormId();
            }
        }
        if (Objects.equals(productListDataDTO.getBusinessType(),XbbRefTypeEnum.WORK_ORDER.getCode())){
            WorkOrderFormEntityExt workOrderFormEntityExt;
            if (Objects.isNull(formId) || Objects.equals(formId,0L)){
                workOrderFormEntityExt = workOrderFormModel.getDefaultAllListForm();
            }else {
                workOrderFormEntityExt = workOrderFormModel.getByKey(formId, corpid);
            }
            paasFormEntityExt = new PaasFormEntityExt();
            BeanUtil.copyProperties(workOrderFormEntityExt,paasFormEntityExt);
        } else if (Objects.equals(productListDataDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) || Objects.equals(productListDataDTO.getBusinessType(), XbbRefTypeEnum.STOCK_SEARCH.getCode())) {
            paasFormEntityExt = paasFormModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
        } else if (Objects.equals(productListDataDTO.getBusinessType(), XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode())) {
            paasFormEntityExt = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PRICE_SET_PRODUCT.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode(), null);
        } else {
            paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        }
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
        explainList.forEach((item) -> {
            explainMap.put(item.getAttr(), item);
        });
        // 分类筛选
        if (productListDataDTO.getCategoryId() != null) {
            List<Long> categoryIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<ProductCategoryEntity> productCategoryList = productCategoryService.getSubCategoryIdList(corpid, productListDataDTO.getCategoryId());
            productCategoryList.forEach((item)->{
                categoryIdIn.add(item.getId());
            });
            if (!categoryIdIn.isEmpty()) {
                conditionsEntityExtList.add(new ConditionsEntityExt(ProductEnum.CATEGORY_ID.getAttr(),"",ProductEnum.CATEGORY_ID.getFieldType(),ConditionEnum.IN.getSymbol(),new ArrayList<>(categoryIdIn)));
            }
        }
        Iterator<ConditionsEntityExt> iterator = conditionsEntityExtList.iterator();
        while (iterator.hasNext()) {
            ConditionsEntityExt entityExt = iterator.next();
            if (entityExt.getAttr().equals(ProductEnum.SPECIFICATION.getAttr())) {
                entityExt.setAttr(ProductEnum.SPECIFICATION_LINK_TEXT.getAttr());
                break;
            }
        }
        List<String> fieldList = BusinessFieldEnum.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
        explainList = explainHelp.handleExplain(explainList, fieldList, paasFormEntityExt);
        //查询
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery("data." + ProductEnum.ENABLE_SKU.getAttr(),1));
        boolQueryBuilder.mustNot(termQuery("data." + ProductEnum.PARENT_ID.getAttr(),0));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        String nameLike = productListDataDTO.getNameLike();
        if (StringUtil.isNotEmpty(nameLike)) {
            BoolQueryBuilder nameLikeBoolQueryBuilder = boolQuery();
            EsUtil.getTermQuery(nameLikeBoolQueryBuilder, productListDataDTO, true);
            nameLikeBoolQueryBuilder.filter(matchPhraseQuery("data." + ProductEnum.SPECIFICATION_LINK_TEXT.getAttr(), nameLike));
            List<String> nameLikeFieldList = new ArrayList<>();
            nameLikeFieldList.add(StringConstant.DATA_ID);
            nameLikeFieldList.add(ProductEnum.getAttrConnectData(ProductEnum.PARENT_ID));
            List<PaasFormDataEntityExt> childProductList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PRODUCT, nameLikeBoolQueryBuilder, PaasFormDataEntityExt.class, nameLikeFieldList);
            Set<Long> parentIdList = new HashSet<>();
            for (PaasFormDataEntityExt entityExt : childProductList) {
                parentIdList.add(entityExt.getData().getLong(ProductEnum.PARENT_ID.getAttr()));
            }
            productListDataDTO.setNameLikeIdIn(parentIdList);
        }
        EsUtil.parseCondition(boolQueryBuilder,conditionsEntityExtList,"",corpid,XbbRefTypeEnum.PRODUCT.getCode());
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.sort(new FieldSortBuilder("updateTime").order(SortOrder.DESC));
        sourceBuilder.query(boolQueryBuilder);
        if (StringUtil.isNotEmpty(nameLike)) {
            List<String> searchAttrList = ListSearchEnum.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(),false);
            BoolQueryBuilder innerBoolQueryBuilder = boolQuery();
            for (String attr : searchAttrList) {
                innerBoolQueryBuilder.should(matchPhraseQuery(attr, nameLike));
            }
            if (Objects.nonNull(productListDataDTO.getNameLikeIdIn()) && !productListDataDTO.getNameLikeIdIn().isEmpty()){
                innerBoolQueryBuilder.should(termsQuery(FieldTypeEnum.DATAID.getAlias(), productListDataDTO.getNameLikeIdIn()));
            }
            innerBoolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
            boolQueryBuilder.filter(innerBoolQueryBuilder);
        }
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD,IndexTypeEnum.IDX_SAAS_PRODUCT.getType()));
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, productListDataDTO.getPage(), productListDataDTO.getPageSize());
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PRODUCT.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
        if (esEntities == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        PageHelper pageHelper = new PageHelper(productListDataDTO.getPage(), productListDataDTO.getPageSize());
        pageHelper.setRowsCount((int) esEntities.getTotalElements());
        formDataListVO.setPageHelper(pageHelper);
        formDataListVO.setPaasFormDataESList(esEntities.getContent());
        productService.setChildSpecification(formDataListVO.getPaasFormDataESList(),productListDataDTO.getCorpid());
        FilterAttrOnOffJXCDTO filterAttrOnOffJXCDTO = new FilterAttrOnOffJXCDTO();
        BeanUtil.copyProperties(productListDataDTO, filterAttrOnOffJXCDTO);
        filterAttrOnOffJXCDTO.setFieldAttrEntityList(explainList);
        filterAttrOnOffJXCDTO.setOperatePageCode(OperatePageEnum.LIST.getCode());
        productModel.filterAttrOnOffJXC(filterAttrOnOffJXCDTO);
        formDataListVO.setHeadList(explainList);
        formDataListVO.setForm(paasFormEntityExt);
        saasListHelp.analysisSaasDataList(formDataListVO, explainMap);
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(productListDataDTO,formDataListDTO);
        // 这里必须设置成产品的业务，不然后面判断高级权限会有bug
        formDataListDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
        explainList.forEach(fieldAttrEntity -> {
            if(Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.SERIALNO.getAttr())){
                fieldAttrEntity.setAttr(ProductEnum.PRODUCT_NO.getAttr());
            }
        });
        formDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);
        if (Objects.equals(productListDataDTO.getSourceBusinessType(), XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode()) || Objects.equals(productListDataDTO.getSourceBusinessType(), XbbRefTypeEnum.WAIT_OUTSTOCK.getCode()) || Objects.equals(productListDataDTO.getSourceBusinessType(), XbbRefTypeEnum.WAIT_PURCHASE.getCode()) || Objects.equals(productListDataDTO.getSourceBusinessType(), XbbRefTypeEnum.SMART_REPLENISHMENT.getCode())){
            Iterator<FieldAttrEntity> iterators = explainList.iterator();
            while (iterators.hasNext()){
                FieldAttrEntity fieldAttrEntity = iterators.next();
                if (Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.PRICE.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.COST.getAttr())){
                    iterators.remove();
                }
            }
            List<PaasFormDataEntityExt>  paasFormDataESList = formDataListVO.getPaasFormDataESList();
            paasFormDataESList.forEach(item ->{
                JSONObject data = item.getData();
                String serialNo = data.getString(ProductEnum.PRODUCT_NO.getAttr());
                data.put("serialNo", serialNo);
            });
        }
        paasFormEntityExt.setBusinessName(XbbRefTypeEnum.getByCode(XbbRefTypeEnum.PRODUCT.getCode()).getName());
        String mainAttr = CommonBusinessFieldUtil.getFormEntityMainAttr(XbbRefTypeEnum.PRODUCT.getCode());
        paasFormEntityExt.setMainAttr(mainAttr);
        formDataListVO.setForm(paasFormEntityExt);
        return formDataListVO;
    }

    /**
     * 采购合同二级筛选
     * @param productListDataDTO
     * @return
     * @throws XbbException
     */
    @Override
    public PaasFormDataEsListVO getPurchaseSearchList(ProductListDataDTO productListDataDTO) throws XbbException {
        String corpid = productListDataDTO.getCorpid();
        Long formId = productListDataDTO.getFormId();
        productListDataDTO.getConditions().addAll(saasListHelp.packagePurchaseCondition(productListDataDTO));
        List<ConditionsEntityExt> conditionsEntityExtList = productListDataDTO.getConditions();
        //解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PURCHASE.getCode(), corpid);
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
        explainList.forEach((item) -> {
            explainMap.put(item.getAttr(), item);
        });
        List<String> fieldList = WaitInstockEnum.getByBusinessType(XbbRefTypeEnum.PURCHASE.getCode());
        explainList = explainHelp.handleExplain(explainList, fieldList, paasFormEntityExt);
        //查询
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
        boolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PURCHASE.getType()));
        String nameLike = productListDataDTO.getNameLike();
        if (StringUtil.isNotEmpty(nameLike)) {
            List<String> searchAttrList = ListSearchEnum.getByBusinessType(XbbRefTypeEnum.PURCHASE.getCode(),false);
            BoolQueryBuilder innerBoolQueryBuilder = boolQuery();
            for (String attr : searchAttrList) {
                innerBoolQueryBuilder.should(matchPhraseQuery(attr, nameLike));
            }
            innerBoolQueryBuilder.minimumShouldMatch(MINI_MUM_SHOULD_MATCH);
            boolQueryBuilder.filter(innerBoolQueryBuilder);
        }
        EsUtil.parseCondition(boolQueryBuilder,conditionsEntityExtList,"",corpid,XbbRefTypeEnum.PURCHASE.getCode());
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.sort(new FieldSortBuilder("updateTime").order(SortOrder.DESC));
        sourceBuilder.query(boolQueryBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, productListDataDTO.getPage(), productListDataDTO.getPageSize());
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_PURCHASE.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, PaasFormDataEntityExt.class);
        if (esEntities == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        PageHelper pageHelper = new PageHelper(productListDataDTO.getPage(), productListDataDTO.getPageSize());
        pageHelper.setRowsCount((int) esEntities.getTotalElements());
        formDataListVO.setPageHelper(pageHelper);
        formDataListVO.setPaasFormDataESList(esEntities.getContent());
        formDataListVO.setHeadList(explainList);
        formDataListVO.setForm(paasFormEntityExt);
        saasListHelp.analysisSaasDataList(formDataListVO, explainMap);
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(productListDataDTO,formDataListDTO);
        List<PaasFormDataEntityExt>  paasFormDataESList = formDataListVO.getPaasFormDataESList();
        paasFormDataESList.forEach(paasFormDataEntityExt -> {
            String serialNo = paasFormDataEntityExt.getSerialNo();
            paasFormDataEntityExt.getData().put(WaitInstockEnum.SHEET_NO.getAttr(), serialNo);
        });
        formDataListAnalysisDataHelp.analysisDataList(formDataListDTO, formDataListVO);
        paasFormEntityExt.setBusinessName(XbbRefTypeEnum.getByCode(XbbRefTypeEnum.PURCHASE.getCode()).getName());
        String mainAttr = paasFormDataModel.getFormEntityMainAttr(XbbRefTypeEnum.PURCHASE.getCode());
        paasFormEntityExt.setMainAttr(mainAttr);
        formDataListVO.setForm(paasFormEntityExt);
        paasFormDataESList.forEach(paasFormDataEntityExt -> {
            JSONArray contractInFo = new JSONArray();
            JSONObject data = paasFormDataEntityExt.getData();
            JSONArray supplierArray = data.getJSONArray(WaitInstockEnum.SUPPLIER_ID.getAttr());
            contractInFo.add(data.get(WaitInstockEnum.SHEET_NO.getAttr()));
            contractInFo.add("采购合同名称："+FastJsonHelper.getStringOrDefault(data, WaitInstockEnum.PURCHASE_NAME.getAttr(), ""));
            if(Objects.nonNull(supplierArray)){
                data.put(WaitInstockEnum.SUPPLIER_ID.getAttr(), supplierArray.getJSONObject(0).getString("name"));
                contractInFo.add("供应商："+supplierArray.getJSONObject(0).getString("name"));
            }
            data.put("contractInFo", contractInFo);
        });
        explainList.forEach(fieldAttrEntity -> {
            if(Objects.equals(fieldAttrEntity.getAttr(), WaitInstockEnum.SUPPLIER_ID.getAttr())){
                fieldAttrEntity.setFieldType(FieldTypeEnum.TEXT.getType());
            }
        });
        return formDataListVO;
    }

    /**
     * 合同二级筛选
     * @param productListDataDTO
     * @return
     * @throws XbbException
     */
    @Override
    public PaasFormDataEsListVO getContractSearchlist(ProductListDataDTO productListDataDTO) throws XbbException {
        productListDataDTO.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
        Integer sourceBusinessType = productListDataDTO.getSourceBusinessType();
        String corpid = productListDataDTO.getCorpid();
        Long formId = productListDataDTO.getFormId();
        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(productListDataDTO,formDataListDTO);
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        PaasFormExplainEntity paasFormExplainEntity=null;
        if (Objects.equals(sourceBusinessType,XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())){
            paasFormExplainEntity=paasFormExplainModel.getByFormId(formId,corpid);
        }else {
            paasFormExplainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.CONTRACT.getCode(), corpid);
        }
        String explains = paasFormExplainEntity.getExplains();
        List<FieldAttrEntity> explainList = JSON.parseArray(explains, FieldAttrEntity.class);
        // 待采购特殊处理
        if (Objects.nonNull(sourceBusinessType) && Objects.equals(sourceBusinessType,XbbRefTypeEnum.WAIT_PURCHASE.getCode())){
            // 获取所有启用的合同订单模版
            List<PaasFormEntityExt> paasFormEntityExtList = paasFormService.getEnableContractFormList(formDataListDTO.getLoginUser());
            List<Long> contractFormIdList = new ArrayList<>();
            List<Long> orderFormIdList = new ArrayList<>();
            // 拿出所有合同表单ID 以及经销商的fromID 用作下面es做聚合时使用
            if (CollectionsUtil.isNotEmpty(paasFormEntityExtList)){
                for (PaasFormEntityExt entityExt : paasFormEntityExtList){
                    if (Objects.equals(entityExt.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                        orderFormIdList.add(entityExt.getId());
                    }else {
                        contractFormIdList.add(entityExt.getId());
                    }
                }
            }
            // 没有模版启用时
            if (CollectionsUtil.isEmpty(contractFormIdList) && CollectionsUtil.isEmpty(orderFormIdList)){
                throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350007);
            }
            List<SortBuilder> sortBuilders = new ArrayList<>();
            // 更新时间倒序排序
            sortBuilders = Collections.singletonList(new FieldSortBuilder(ContractEnum.UPDATE_TIME.getAttr()).order(SortOrder.DESC));
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            // 查询合同订单有产品 且出库状态不是全部出库且不是关闭的的 且未归档 更新时间倒序排序 del= 0
            BoolQueryBuilder contractBoolQueryBuilder = boolQuery();
            if (CollectionsUtil.isNotEmpty(contractFormIdList)){
                contractBoolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                contractBoolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
                contractBoolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                contractBoolQueryBuilder.filter(termsQuery(ParameterConstant.FORMID,contractFormIdList));
                contractBoolQueryBuilder.filter(termsQuery("flowStatus",FlowStatusEnum.getStatisticType()));
                contractBoolQueryBuilder.filter(existsQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.PRODUCT).replace(".keyword", "")));
                contractBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ARCHIVED), ArchivedEnum.ARCHIVED.getCode()));
                contractBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ALL_OUT_BOUND), AllOutBoundEnum.ALL_OUT.getCode()));
                contractBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SHIP_STATUS), ShipStatusEnum.CLOSED.getCode()));
                contractBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.SHIP_STATUS), ShipStatusEnum.SHIPPED.getCode()));
                // TODO 创建时间大于上线日期 暂时写为2022-03-10
                contractBoolQueryBuilder.filter(rangeQuery(ParameterConstant.ADD_TIME).gte(BasicConstant.JXC_ONLINE_DATE));
                boolQueryBuilder.should(contractBoolQueryBuilder);

            }
            // 如果有经销商的订单的 需要过滤订单状态
            if (CollectionsUtil.isNotEmpty(orderFormIdList)){
                List<String> orderStatusList = new ArrayList<>();
                orderStatusList.add(OrderStatusEnum.DELIVERED.getCode());
                orderStatusList.add(OrderStatusEnum.RECEIVED.getCode());
                // 查询订货单有产品 且出库状态不是全部出库且不是关闭的的 且未归档  订单状态未待发货 或者待收货 更新时间倒序排序 del= 0
                BoolQueryBuilder orderBoolQueryBuilder = boolQuery();
                orderBoolQueryBuilder.filter(termQuery("corpid.keyword",corpid));
                orderBoolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
                orderBoolQueryBuilder.filter(termQuery(StringConstant.DEL,DelEnum.NORMAL.getDel()));
                orderBoolQueryBuilder.filter(termsQuery(ParameterConstant.FORMID,orderFormIdList));
                orderBoolQueryBuilder.filter(termQuery(ContractEnum.STATUS.getAttr(),orderStatusList));
                orderBoolQueryBuilder.filter(termsQuery("flowStatus",FlowStatusEnum.getStatisticType()));
                orderBoolQueryBuilder.filter(existsQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.PRODUCT).replace(".keyword", "")));
                orderBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ARCHIVED), ArchivedEnum.ARCHIVED.getCode()));
                orderBoolQueryBuilder.mustNot(termQuery(ContractEnum.getEsAttr4Keyword(ContractEnum.ALL_OUT_BOUND), AllOutBoundEnum.ALL_OUT.getCode()));
                // TODO 创建时间大于等于上线日期 暂时写为2022-03-10
                orderBoolQueryBuilder.filter(rangeQuery(ParameterConstant.ADD_TIME).gte(BasicConstant.JXC_ONLINE_DATE));
                boolQueryBuilder.should(orderBoolQueryBuilder);
            }
            boolQueryBuilder.minimumShouldMatch(1);
            if (Objects.nonNull(formDataListDTO.getConditions())){
                EsUtil.parseCondition(boolQueryBuilder,formDataListDTO.getConditions(),"",corpid,XbbRefTypeEnum.WAIT_PURCHASE.getCode());
            }
            XbbAggregatedPage aggregatedPage;
            try {
                aggregatedPage = esHelper.findByPage(IndexTypeEnum.IDX_SAAS_CONTRACT, boolQueryBuilder, PaasFormDataEntityExt.class, null,formDataListDTO.getPage(),formDataListDTO.getPageSize(),sortBuilders);
            } catch (Exception e) {
                aggregatedPage = null;
                LOG.info("待采购列表es数据查询失败");
            }
            formDataListVO.setPaasFormDataESList(aggregatedPage.getContent());
            formDataListVO.getPageHelper().setRowsCount((int)aggregatedPage.getTotalElements());
            Map<String,FieldAttrEntity> explainMap = new HashMap<>();
            if (CollectionsUtil.isNotEmpty(explainList)){
                explainList.forEach(item -> explainMap.put(item.getAttr(),item));
            }
            formDataListDTO.setExplainMap(explainMap);
            formDataListVO.setHeadList(explainList);
        }else {
            List<ConditionsEntityExt> conditionsEntityExtList = productListDataDTO.getConditions() == null ? new ArrayList<>() : productListDataDTO.getConditions();
            //解释
            //兼容经销商订货单
            if (Objects.equals(productListDataDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                //如果是出库退货单中关联订货单，这个订货单的订单状态有要求,订单状态必须为待发货
                ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(OrderEnum.STATUS.getAttr(), "", OrderEnum.STATUS.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(OrderStatusEnum.DELIVERED.getCode()));
                conditionsEntityExtList.add(conditionsEntityExt);
            }

            conditionsEntityExtList.addAll(saasListHelp.packageWaitOutstockCondition(formDataListDTO));
            formDataListVO = formDataListSearchHelp.getEsList(formDataListDTO);
        }
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        List<String> fieldList = new ArrayList<>();
        if (Objects.nonNull(sourceBusinessType) && Objects.equals(sourceBusinessType, XbbRefTypeEnum.WAIT_OUTSTOCK.getCode())) {
            fieldList = BusinessFieldEnum.getByBusinessType(XbbRefTypeEnum.WAIT_OUTSTOCK.getCode());
        } else {
            fieldList = BusinessFieldEnum.getByBusinessType(XbbRefTypeEnum.WAIT_PURCHASE.getCode());
        }
        explainList = explainHelp.handleExplain(explainList, fieldList, paasFormEntityExt);
        formDataListVO.setHeadList(explainList);
        formDataListSearchHelp.webDataAnalysis(formDataListDTO, formDataListVO);
        formDataListVO.getPaasFormDataESList().forEach(paasFormDataEntityExt -> {
            JSONObject data = paasFormDataEntityExt.getData();
            String serialNo = paasFormDataEntityExt.getSerialNo();
            JSONArray contractInFo = new JSONArray();
            contractInFo.add(serialNo);
            if (Objects.nonNull(data.get(ContractEnum.NAME.getAttr()))) {
                contractInFo.add("合同名称：" + data.get(ContractEnum.NAME.getAttr()));
            } else {
                contractInFo.add("合同名称：" + "");
            }
            JSONArray customerArray = data.getJSONArray(ContractEnum.LINK_CUSTOMER.getAttr());
            if (Objects.nonNull(customerArray)) {
                contractInFo.add("客户名称：" + customerArray.getJSONObject(0).getString("name"));
                data.put(ContractEnum.LINK_CUSTOMER.getAttr(), customerArray.getJSONObject(0).getString("name"));
            } else {
                if (Objects.nonNull(data.get(ContractEnum.LINK_CUSTOMER.getAttr()))) {
                    contractInFo.add("客户名称：" + data.get(ContractEnum.LINK_CUSTOMER.getAttr()));
                } else {
                    contractInFo.add("客户名称：" + "");
                }
            }
            data.put("contractInFo", contractInFo);
        });
        Iterator<FieldAttrEntity> iterator = explainList.iterator();
        while (iterator.hasNext()){
            FieldAttrEntity fieldAttrEntity = iterator.next();
            String contractAttr = fieldAttrEntity.getAttr();
            if (Objects.equals(contractAttr, ContractEnum.LINK_CUSTOMER.getAttr())) {
                fieldAttrEntity.setFieldType(FieldTypeEnum.TEXT.getType());
            }
            if (Objects.equals(contractAttr, ContractEnum.OWNER_ID.getAttr())||Objects.equals(contractAttr, ContractEnum.MINOR_USER.getAttr())){
                fieldAttrEntity.setFieldType(FieldTypeEnum.TEXT.getType());
            }
        }
        formDataListVO.setHeadList(explainList);
        return formDataListVO;
    }

    /**
     * 选择仓库后校检是否可选
     * @param warehouseCheckDTO
     * @return
     * @throws XbbException
     */
    @Override
    public WarehouseListVO checkWarehouse(WarehouseCheckDTO warehouseCheckDTO) throws XbbException {
        WarehouseListVO warehouseListVO = new WarehouseListVO();
        Integer businessType = warehouseCheckDTO.getBusinessType();
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case INVENTORY:
                warehouseListVO = inventoryService.checkWarehouse(warehouseCheckDTO);
            default:
                break;
        }
        return warehouseListVO;
    }


    @Override
    public CustomerMergeVO getCustomerMerge(FormDataListDTO formDataListDTO) throws XbbException {

        CustomerMergeVO customerMergeVO = new CustomerMergeVO();
        List<Long> idIn = formDataListDTO.getIdIn();
        Integer businessType = formDataListDTO.getSubBusinessType();
        PaasFormDataEsListVO formDataListVO = null;
        // 写死就可以了， 最多就只会有两条
        formDataListDTO.setPage(1);
        formDataListDTO.setPageSize(2);
        formDataListDTO.setConditions(formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions());
        formDataListDTO.getConditions().add(EsUtil.packageContions(StringConstant.DATA_ID, new ArrayList<>(idIn), ConditionEnum.IN, FieldTypeEnum.DATAID.getType()));
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        switch (xbbRefTypeEnum) {
            case CUSTOMER:
            case CUSTOMER_FOCUS:
            case CUSTOMER_DEAL:
            case CUSTOMER_FOLLOW:
            default:
                formDataListVO = saasListService.customerList(formDataListDTO);
                break;
            case CUSTOMER_PUBLIC:
                formDataListVO = saasListService.publicCustomer(formDataListDTO);
                break;
            case CUSTOMER_RECYCLE:
                formDataListVO = saasListService.delCustomerList(formDataListDTO);
                formDataListDTO.setDel(DelEnum.NORMAL.getDel());
                break;
        }
        List<FieldAttrEntity> headList = formDataListVO.getHeadList();
        List<PaasFormDataEntityExt> paasFormDataESList = formDataListVO.getPaasFormDataESList();
        if (!Objects.equals(paasFormDataESList.size(), BasicConstant.TWO)){
            throw  new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        JSONObject data = paasFormDataESList.get(0).getData();
        JSONObject data1 = paasFormDataESList.get(1).getData();
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        HandlerExplainDTO handlerExplainDTO1 = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO);
        BeanUtil.copyProperties(formDataListDTO, handlerExplainDTO1);
        handlerExplainDTO.setCreatorId(paasFormDataESList.get(0).getCreatorId());
        handlerExplainDTO1.setCreatorId(paasFormDataESList.get(1).getCreatorId());
        List<FieldAttrEntityForMerge> headList1 = new ArrayList<>();
        // 添加主客户字段,
        FieldAttrEntityForMerge fieldAttrEntityForMergeForMain = new FieldAttrEntityForMerge();
        fieldAttrEntityForMergeForMain.setAttr("mainCustomer");
        fieldAttrEntityForMergeForMain.setAttrName("主客户");
        headList1.add(fieldAttrEntityForMergeForMain);
        for (FieldAttrEntity item : headList) {
            Boolean aBoolean = ExplainUtil.invisibleOfScope(item, handlerExplainDTO);
            Boolean aBoolean1 = ExplainUtil.invisibleOfScope(item, handlerExplainDTO1);
            if (aBoolean){
                if (Objects.equals(item.getFieldType(), FieldTypeEnum.SUB_FORM.getType()) || Objects.equals(item.getFieldType(), FieldTypeEnum.CONTACT_NUMBER.getType())) {
                    data.put(item.getAttr(), new ArrayList());
                } else {
                    data.put(item.getAttr(), "--");
                }
            }

            if (aBoolean1){
                if (Objects.equals(item.getFieldType(), FieldTypeEnum.SUB_FORM.getType()) || Objects.equals(item.getFieldType(), FieldTypeEnum.CONTACT_NUMBER.getType())) {
                    data1.put(item.getAttr(), new ArrayList());
                } else {
                    data1.put(item.getAttr(), "--");
                }
            }
            if (Objects.nonNull(ListOptionEnum.getByAttr(item.getAttr()))) {
                continue;
            }
            if (removeNotShowAttr(item)){
                continue;
            }
            // 客户公海池不展示前负责人
            if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode()) && Objects.equals(item.getAttr(), "ownerId")){
                continue;
            }
            FieldAttrEntityForMerge fieldAttrEntityForMerge = new FieldAttrEntityForMerge();
            BeanUtil.copyProperties(item, fieldAttrEntityForMerge);
            headList1.add(fieldAttrEntityForMerge);
        }
        customerMergeVO.setExplainList(headList1);
        customerMergeVO.setPaasFormEntity(formDataListVO.getForm());
        customerMergeVO.setCustomerEntityExtList(formDataListVO.getPaasFormDataESList());
        //判断当前表单模式
        boolean formShareTag = userTeamHelp.getFormShareTag(formDataListDTO.getCorpid(), formDataListDTO.getFormId(), formDataListDTO.getBusinessType());
        if (formShareTag) {
            customerMergeVO.setModel(FormPatternEnum.FORM_SHARE.getModel());
        }else {
            customerMergeVO.setModel(FormPatternEnum.FORM_ISOLATION.getModel());
        }
        return customerMergeVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PaymentWriteOffVO paymentWriteOff(PaymentWriteOffDTO paymentWriteOffDTO) throws XbbException {
        JSONObject data = paymentWriteOffDTO.getData();
        String corpid = paymentWriteOffDTO.getCorpid();
        double amount = data.getDoubleValue(PaymentWriteOffEnum.AMOUNT.getAttr());
        if (amount <= 0) {
            throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208070, PaymentErrorCodeEnum.API_ERROR_208070.getMsg());
        }
        JSONArray paymentArr = data.getJSONArray(PaymentWriteOffEnum.PAYMENT.getAttr());
        if (CollectionsUtil.isEmpty(paymentArr)) {
            throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208071, PaymentErrorCodeEnum.API_ERROR_208071.getMsg());
        }
        JSONArray sheetArr = data.getJSONArray(PaymentWriteOffEnum.PAYMENT_SHEET_ID.getAttr());
        if (CollectionsUtil.isEmpty(sheetArr)) {
            throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208072, PaymentErrorCodeEnum.API_ERROR_208072.getMsg());
        }
        Long paymentId = paymentArr.getJSONObject(0).getLong(BasicConstant.ID);
        PaymentEntityExt paymentEntityExt = paymentModel.getByKey(paymentId, corpid);
        if (Objects.isNull(paymentEntityExt)) {
            throw new XbbException(RaidersErrorCodeEnum.API_ERROR_800005, String.format(RaidersErrorCodeEnum.API_ERROR_800005.getMsg(), XbbRefTypeEnum.PAYMENT.getName()));
        }
        JSONObject paymentData = JsonHelperUtil.getJSONObject(paymentEntityExt.getData());
        //有未收才能核销
        double unAmount = paymentData.getDoubleValue(PaymentBaseEnum.UN_AMOUNT.getAttr());
        if (unAmount < amount) {
            throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208073, String.format(PaymentErrorCodeEnum.API_ERROR_208073.getMsg(), StringUtil.formatDouble(unAmount)));
        }
        Long sheetId = sheetArr.getJSONObject(0).getLong(BasicConstant.ID);
        PaymentSheetEntityExt sheetEntityExt = paymentSheetModel.getByKey(sheetId, corpid);
        if (Objects.isNull(sheetEntityExt)) {
            throw new XbbException(RaidersErrorCodeEnum.API_ERROR_800005, String.format(RaidersErrorCodeEnum.API_ERROR_800005.getMsg(), XbbRefTypeEnum.PAYMENT_SHEET.getName()));
        }
        JSONObject sheetData = JsonHelperUtil.getJSONObject(sheetEntityExt.getData());
        String sheetType = sheetData.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr());
        if (!PaymentSheetTypeEnum.isWriteOff(sheetType)) {
            throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208074, PaymentErrorCodeEnum.API_ERROR_208074.getMsg());
        }
        //不能超出回款单可核销金额
        double sheetAmount = FundHelp.getSheetAmount4PaymentSheet(sheetData, sheetType);
        if (!Objects.equals(sheetAmount, amount)) {
            throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208075, String.format(PaymentErrorCodeEnum.API_ERROR_208075.getMsg(), StringUtil.formatDouble(sheetAmount)));
        }
        PaymentSheetTypeEnum paymentSheetTypeEnum = PaymentSheetTypeEnum.getByCode(sheetType);
        Integer alone = sheetEntityExt.getAlone();
        Set<Long> paymentIds = new HashSet<>();
        paymentIds.add(paymentId);
        List<String> paymentNos = Arrays.asList(paymentEntityExt.getSerialNo());
        sheetData.put(PaymentSheetBaseEnum.PAYMENT.getAttr(), paymentIds);
        sheetData.put(PaymentSheetBaseEnum.PAYMENT_LINK_TEXT.getAttr(), paymentNos);
        sheetEntityExt.setData(sheetData);
        long now = DateTimeUtil.getInt();
        sheetEntityExt.setUpdateTime(now);
        List<PaasFormDataEntityExt> updateSheetList = new ArrayList<>();
        updateSheetList.add(sheetEntityExt);
        List<Long> sheetIds = new ArrayList<>();
        sheetIds.add(sheetId);
        if (Objects.equals(alone, SheetAloneEnum.CHILD.getCode())) {
            List<PaasFormDataEntityExt> parentList = fundHelp.getEsDataListByUuidAndAlone(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET, corpid, SheetAloneEnum.PARENT, sheetEntityExt.getUuid(), null);
            if (parentList.size() > 0) {
                PaasFormDataEntityExt parentEntity = parentList.get(0);
                JSONObject parentData = JsonHelperUtil.getJSONObject(parentEntity.getData());
                List<Long> parentPaymentIdList = FastJsonHelper.getJsonArrOrDefaultFromFormData(parentData, PaymentSheetEnum.PAYMENT.getAttr(), new JSONArray()).toJavaList(Long.class);
                if (!parentPaymentIdList.contains(paymentId)) {
                    parentPaymentIdList.add(paymentId);
                    JSONArray parentPaymentNoArr = FastJsonHelper.getJsonArrFromFormData(parentData, PaymentSheetEnum.PAYMENT_LINK_TEXT.getAttr());
                    parentPaymentNoArr.add(paymentEntityExt.getSerialNo());
                    parentData.put(PaymentSheetBaseEnum.PAYMENT.getAttr(), parentPaymentIdList);
                    parentData.put(PaymentSheetBaseEnum.PAYMENT_LINK_TEXT.getAttr(), parentPaymentNoArr);
                    parentEntity.setData(parentData);
                    parentEntity.setUpdateTime(now);
                    updateSheetList.add(parentEntity);
                    sheetIds.add(parentEntity.getId());
                }
            }
        }
        try {
            paymentSheetModel.updateBatchForData(updateSheetList, corpid);
            Map<Long, Double> paymentIdToAmount = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paymentIdToAmount.put(paymentId, amount);
            //处理应收款并封装要更新的结果：判断已收金额是否已经超过应收款内的未收金额，并把应收款的已收金额增加及更改其回款状态等
            HandleLinkInfoVO paymentLinkInfoVO = paymentService.handlePayment(paymentSheetTypeEnum, sheetData, corpid, paymentIdToAmount, paymentIds);
            List<UpdateDataEntity> updatePayList = paymentLinkInfoVO.getUpdateList();
            //更新应收款
            paymentModel.savePaymentPlan(corpid, updatePayList);
        }catch (XbbException e){
            //应收核销失败，回滚异步
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(() -> {
                try {
                    Thread.sleep(1000L);
                    paymentSheetService.updateRollback(sheetIds, corpid);
                    //被更新的关联业务es回滚至更改之前（通过查数据库）
                    paymentService.updateRollback(paymentIds, corpid);
                } catch (XbbException | InterruptedException e1) {
                    LOG.error("paymentWriteOff rollback" + e1);
                    // 恢复中断状态
                    Thread.currentThread().interrupt();
                }
            });
            throw e;
        }catch (Exception e){
            //应收核销失败，回滚异步
            threadPoolBeanConfig.addUpdateDelThreadPool().execute(() -> {
                try {
                    Thread.sleep(1000L);
                    paymentSheetService.updateRollback(sheetIds, corpid);
                    //被更新的关联业务es回滚至更改之前（通过查数据库）
                    paymentService.updateRollback(paymentIds, corpid);
                } catch (XbbException | InterruptedException e1) {
                    LOG.error("paymentWriteOff rollback" + e1);
                    // 恢复中断状态
                    Thread.currentThread().interrupt();
                }
            });
            LOG.error("应收款核销失败", e);
            throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208076, PaymentErrorCodeEnum.API_ERROR_208076.getMsg());
        }
        return new PaymentWriteOffVO();
    }

    @Override
    public PaasFormDataEsListVO purchaseIdListByEs(FormDataListDTO formDataListDTO , List<PurchaseProductEntity> purchaseProduct,Map<String, Object> param) throws XbbException{
        PaasFormDataEsListVO formDataListVO;
        List<Long> purchaseIds = new ArrayList();
        try{
            //获得关联合同id集合
            purchaseProduct.forEach(purchaseProductEntity -> purchaseIds.add(purchaseProductEntity.getPurchaseSheetId()));
            formDataListDTO.getConditions().addAll(saasListHelp.purchaseWaitInstockCondition(purchaseIds));
            //查询采购合同产品关联表总条数
            Integer num = purchaseProductService.getPurchaseProductCount(param);
            PageHelper pageHelper = new PageHelper(formDataListDTO.getPage(), formDataListDTO.getPageSize());
            pageHelper.setRowsCount(num);
            //重新封装参数
            formDataListDTO.setPurchaseProductEntityList(purchaseProduct);
            formDataListDTO.setPage(1);
            //查询合同数据
            formDataListDTO.setBusinessType(XbbRefTypeEnum.PURCHASE.getCode());
            formDataListVO = formDataListSearchHelp.getEsList(formDataListDTO);
            formDataListVO.setPageHelper(pageHelper);
            //处理合同编号穿透
            List<FieldAttrEntity> explainLists = formDataListVO.getHeadList();
            for(FieldAttrEntity fieldAttrEntity : explainLists){
                if (!Objects.equals(fieldAttrEntity.getAttr(),WaitInstockEnum.ADDTIME.getAttr()) && !Objects.equals(fieldAttrEntity.getAttr(),WaitInstockEnum.UPDATETIME.getAttr())){
                    fieldAttrEntity.setDisableListSort(BasicConstant.ONE);
                }
                if(Objects.equals(fieldAttrEntity.getAttr(),WaitInstockEnum.SHEET_NO.getAttr()) || Objects.equals(fieldAttrEntity.getAttr(),WaitInstockEnum.PURCHASE_NAME.getAttr())){
                    fieldAttrEntity.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                }
            }
            //获取采购合同关联产品解释
            formDataListDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
            List<FieldAttrEntity> explainList = saasListHelp.setProductFormExplain(formDataListDTO,formDataListVO);
            formDataListVO.getHeadList().addAll(explainList);
            if ( PlatFormEnum.WEB.getValue().equals(formDataListDTO.getPlatform()) ) {
                formDataListSearchHelp.webDataAnalysis(formDataListDTO, formDataListVO);
            } else if ( PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform()) ) {
                formDataListVO = formDataListSearchHelp.appDataAnalysis(formDataListDTO, formDataListVO);
            }
            /* ==================== 上部按钮权限和下部按钮权限 ==================== */
            formDataListSearchHelp.setButtons(formDataListDTO, formDataListVO);
            //表单冻结和隐藏列设置（在按钮设置后处理，防止操作列无法冻结和隐藏）
            formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, formDataListVO);
            if (Objects.equals(formDataListVO.getUpdateTime(), formDataListDTO.getUpdateTime())) {
                formDataListVO.setHeadList(new ArrayList<>());
            }
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataListVO;
    }

    @Override
    public PaasFormDataEsListVO productViewListByEs(FormDataListDTO formDataListDTO) throws XbbException {
        PaasFormDataEsListVO formDataListVO = new PaasFormDataEsListVO();
        try{
        //获取符合条件的合同数据
        List<Long> contractEsIds= paasFormDataService.getContractsByEs(formDataListDTO);
        if (!contractEsIds.isEmpty()){
            Map<String, Object> param = contractProductService.getWaitOutStockParam(formDataListDTO, contractEsIds);
            List<ContractProductEntity> waitOutProductEntitys = contractProductService.findWaitOutProductEntitys(param);
            Integer num = contractProductService.findWaitOutStockProductCount(param);
            List<Long> contractIds = new ArrayList();
            for (ContractProductEntity contractProductEntity : waitOutProductEntitys) {
                contractIds.add(contractProductEntity.getContractId());
            }
            formDataListDTO.getConditions().addAll(saasListHelp.purchaseWaitInstockCondition(contractIds));
            //封装分页参数
            PageHelper pageHelper = new PageHelper(formDataListDTO.getPage(), formDataListDTO.getPageSize());
            //查询合同数据
            formDataListDTO.setPage(1);
            //formDataListDTO.setPageSize(1);
            formDataListDTO.setBusinessType(XbbRefTypeEnum.CONTRACT.getCode());
            formDataListVO = formDataListSearchHelp.getEsList(formDataListDTO);
            formDataListDTO.setContractProductEntityList(waitOutProductEntitys);
            pageHelper.setRowsCount(num);
            formDataListVO.setPageHelper(pageHelper);
            //获取产品解释
            formDataListDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(formDataListDTO.getBusinessType(),formDataListDTO.getCorpid());
            if (paasFormExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            //设置表头和解释
            setWaitOutstackFormExplain(paasFormExplainEntity,formDataListDTO,formDataListVO);
           //如果未查询到合同，则返回空
            if (formDataListVO.getPaasFormDataESList().isEmpty()){
                pageHelper.setRowsCount(BasicConstant.ZERO);
                formDataListVO.setPageHelper(pageHelper);
            }
            if (!formDataListVO.getPaasFormDataESList().isEmpty()){
            if ( PlatFormEnum.WEB.getValue().equals(formDataListDTO.getPlatform()) ) {
                formDataListSearchHelp.webDataAnalysis(formDataListDTO, formDataListVO);
            } else if ( PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform()) ) {
                formDataListVO = formDataListSearchHelp.appDataAnalysis(formDataListDTO, formDataListVO);
            }
            }
        }else {
            //无数据则拼接空表头返回
            PageHelper pageHelper = new PageHelper(formDataListDTO.getPage(), formDataListDTO.getPageSize());
            pageHelper.setRowsCount(BasicConstant.ZERO);
            formDataListVO.setPageHelper(pageHelper);
            //表单获取
            PaasFormEntityExt form = formDataListSearchHelp.getForm(formDataListDTO);
            formDataListVO.setForm(form);
            HandleExplainPojo handleExplainPojo = formDataListSearchHelp.handleExplain(formDataListDTO);
            List<FieldAttrEntity> explainList = handleExplainPojo.getExplainList();
            formDataListVO.setUpdateTime(handleExplainPojo.getUpdateTime());
            formDataListVO.setForm(form);
            formDataListVO.setHeadList(explainList);
            formDataListVO.setExplainMap(formDataListDTO.getExplainMap());
            //获取产品解释
            formDataListDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
            PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(formDataListDTO.getBusinessType(), formDataListDTO.getCorpid());
            if (paasFormExplainEntity == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            //设置表头和解释
            setWaitOutstackFormExplain(paasFormExplainEntity, formDataListDTO, formDataListVO);
            formDataListVO.getHeadList().sort(Comparator.comparingInt(FieldAttrEntity::getSort));
        }
            /* ==================== 上部按钮权限和下部按钮权限 ==================== */
            formDataListSearchHelp.setButtons(formDataListDTO, formDataListVO);
            //表单冻结和隐藏列设置（在按钮设置后处理，防止操作列无法冻结和隐藏）
            formDataListSearchHelp.setFixedAndInvisible(formDataListDTO, formDataListVO);
            if (Objects.equals(formDataListVO.getUpdateTime(), formDataListDTO.getUpdateTime())) {
                formDataListVO.setHeadList(new ArrayList<>());
            }
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataListVO;
    }

    @Override
    public List<Long> getContractsByEs(FormDataListDTO formDataListDTO) throws XbbException{
        try {
            String corpid = formDataListDTO.getCorpid();
            Long formId = formDataListDTO.getFormId();
            List<Long> contractIds = new ArrayList<>();
            if (Objects.equals(formDataListDTO.getPlatform(), PlatFormEnum.DINGTALK.getValue())) {
                List<ConditionsEntityExt> conditionsEntityExtList = formDataListDTO.getConditions() == null ? new ArrayList<>() : formDataListDTO.getConditions();
                if (Objects.equals(formDataListDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    //如果是出库退货单中关联订货单，这个订货单的订单状态有要求,订单状态必须为待发货
                    ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt(OrderEnum.STATUS.getAttr(), "", OrderEnum.STATUS.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(OrderStatusEnum.DELIVERED.getCode()));
                    conditionsEntityExtList.add(conditionsEntityExt);
                }
                conditionsEntityExtList.addAll(saasListHelp.packageWaitOutstockCondition(formDataListDTO));
            }
            List<SortBuilder> sortBuilders = new ArrayList<>();
            sortBuilders = Collections.singletonList(new FieldSortBuilder(ContractEnum.UPDATE_TIME.getAttr()).order(SortOrder.DESC));
            // 查询合同订单有产品 且出库状态不是全部出库且不是关闭的的 且未归档 更新时间倒序排序 del= 0
            BoolQueryBuilder contractBoolQueryBuilder = boolQuery();
            contractBoolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            contractBoolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT.getType()));
            contractBoolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            contractBoolQueryBuilder.filter(termQuery(ParameterConstant.FORMID, formId));
            contractBoolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
            // 限制返回值
            List<String> fieldList = Arrays.asList(FieldTypeEnum.DATAID.getAlias());
            if (Objects.nonNull(formDataListDTO.getConditions())) {
                EsUtil.parseCondition(contractBoolQueryBuilder, formDataListDTO.getConditions(), formDataListDTO.getRel(), formDataListDTO.getCorpid(), XbbRefTypeEnum.CONTRACT.getCode());
            }
            //解析或条件
            EsUtil.parseShouldCondition(contractBoolQueryBuilder,formDataListDTO.getShouldConditions(),formDataListDTO.getRel(),formDataListDTO.getCorpid(),formDataListDTO.getBusinessType());
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_CONTRACT, contractBoolQueryBuilder, PaasFormDataEntityExt.class, fieldList, sortBuilders);
            if (!paasFormDataEntityExtList.isEmpty()) {
                for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExtList) {
                    paasFormDataEntityExt.setTagData(new JSONObject());
                    contractIds.add(paasFormDataEntityExt.getDataId());
                }
            }
            return contractIds;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    @Override
    public WaitPurchaseDetailVO productStockSearch(OrderOnPinDTO orderOnPinDTO) throws XbbException {
        WaitPurchaseDetailVO waitPurchaseDetailVO = new WaitPurchaseDetailVO();
        String corpid = orderOnPinDTO.getCorpid();
        Long contractId = orderOnPinDTO.getContractId();
        Long productId = orderOnPinDTO.getProductId();
        Double stockNum = 0D;
        Double purchasePassageNum = 0D;
        boolean isEnglish = false;
        String locale = orderOnPinDTO.getLocale();
        if (Objects.equals(locale,"en_US")){
            isEnglish = true;
        }
        ProductEntityExt productEntityExt = productModel.getByKey(productId, corpid);
        if(Objects.nonNull(productEntityExt)){
            stockNum = productEntityExt.getNum();
        }
        List<PurchaseProductEntity> purchaseProductEntityList = purchaseProductModel.getPurchaseByContract(corpid, Collections.singletonList(contractId));
        if (CollectionsUtil.isNotEmpty(purchaseProductEntityList)){
            for (PurchaseProductEntity entity : purchaseProductEntityList) {
                if (Objects.equals(productId, entity.getProductId())){
                    purchasePassageNum += Arith.sub(entity.getProductNum(),entity.getInstockNum());
                }
            }
        }
        waitPurchaseDetailVO.setStockNum(stockNum);
        waitPurchaseDetailVO.setPurchasePassageNum(purchasePassageNum);
        List<FieldAttrEntity> headList = new ArrayList<>();
        FieldAttrEntity stockAttrEntity = new FieldAttrEntity();
        stockAttrEntity.setAttr("stockNum");
        stockAttrEntity.setAttrName("库存数量");
        FieldAttrEntity purchaseAttrEntity = new FieldAttrEntity();
        purchaseAttrEntity.setAttr("purchasePassageNum");
        purchaseAttrEntity.setAttrName("待入库数量");
        if(isEnglish){
            stockAttrEntity.setAttrName("stockNum");
            purchaseAttrEntity.setAttrName("purchasePassageNum");
        }
        headList.add(stockAttrEntity);
        headList.add(purchaseAttrEntity);
        if(Objects.nonNull(productEntityExt)){
            // 查询产品解释 控制库存数量可见权限
            PaasFormExplainEntity productExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PRODUCT.getCode(), corpid);
            if (Objects.isNull(productExplain) || StringUtils.isEmpty(productExplain.getExplains())){
                waitPurchaseDetailVO.setStockNum(null);
            }
            // 判断改人员是否有可见权限
            UserVO loginUser = orderOnPinDTO.getLoginUser();
            List<FieldAttrEntity> fieldAttrEntityList = JSON.parseArray(productExplain.getExplains(), FieldAttrEntity.class);
            List<FieldAttrEntity> stockAttrList = new ArrayList<>();
            if (CollectionsUtil.isNotEmpty(fieldAttrEntityList)){
                for (FieldAttrEntity item : fieldAttrEntityList) {
                    if (Objects.equals(ProductEnum.STOCK.getAttr(),item.getAttr())){
                        stockAttrList.add(item);
                        break;
                    }
                }
            }
            if (CollectionsUtil.isNotEmpty(stockAttrList)){
                Map<String, FieldAttrEntity> expalinMap = ExplainUtil.getExplainMapByList(stockAttrList);
                ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
                userAndDepartmentGetDTO.setLoginUser(loginUser);
                userAndDepartmentGetDTO.setUserId(orderOnPinDTO.getUserId());
                userAndDepartmentGetDTO.setCorpid(corpid);
                UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
                Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
                Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
                parseSingleRowDataDTO.setExplainMap(expalinMap);
                parseSingleRowDataDTO.setUserMap(userMap);
                parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                parseSingleRowDataDTO.setLoginUser(loginUser);
                parseSingleRowDataDTO.setCorpid(corpid);
                parseSingleRowDataDTO.setUserId(orderOnPinDTO.getUserId());
                JSONObject data = productEntityExt.getData();
                String ownerId = productEntityExt.getOwnerId();
                String creatorId = productEntityExt.getCreatorId();

                Map<String, Boolean> canSeeMap = saasListHelp.parseCanseeParam(stockAttrList, creatorId, Collections.singletonList(ownerId), new ArrayList<>(), parseSingleRowDataDTO);
                if (!canSeeMap.isEmpty()){
                    for (Map.Entry<String, Boolean> stringBooleanEntry : canSeeMap.entrySet()) {
                        String key = stringBooleanEntry.getKey();
                        Boolean value = stringBooleanEntry.getValue();
                        if (!value ){
                            if (Objects.equals(ProductEnum.STOCK.getAttr(),key)){
                                waitPurchaseDetailVO.setStockNum(null);
                            }
                        }
                    }
                }
            }
        }
        waitPurchaseDetailVO.setHeadList(headList);
        return waitPurchaseDetailVO;
    }

    @Override
    public WaitPurchaseConfiglVO getWaitPurchaseConfig(BaseDTO baseDTO) throws XbbException {
        WaitPurchaseConfiglVO waitPurchaseConfiglVO = new WaitPurchaseConfiglVO();
        String corpid = baseDTO.getCorpid();
        // 采购在途公司级配置
        CompanyConfigEntity purchasePassageConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_PURCHASE_PASSAGE.getAlias(), corpid);
        if (Objects.isNull(purchasePassageConfig) || Objects.equals(BasicConstant.IS_USE.toString(),purchasePassageConfig.getConfigValue())){
            waitPurchaseConfiglVO.setEnablePurchasePassage(1);
        }else {
            waitPurchaseConfiglVO.setEnablePurchasePassage(0);
        }
        // 最低库存公司级配置
        CompanyConfigEntity miniStockConfig = companyConfigModel.getByConfigAlias(CompanyConfigEnum.ENABLE_MINI_STOCK.getAlias(), corpid);
        if (Objects.isNull(miniStockConfig) || Objects.equals(BasicConstant.IS_USE.toString(),miniStockConfig.getConfigValue())){
            waitPurchaseConfiglVO.setEnableMiniStock(1);
        }else {
            waitPurchaseConfiglVO.setEnableMiniStock(0);
        }
        return waitPurchaseConfiglVO;
    }

    @Override
    public RepeatFieldListVO getRepeatField(RepeatToolFieldGetDTO repeatToolFieldGetDTO) throws XbbException {
        RepeatFieldListVO repeatFieldListVO = null;
        try {
            repeatFieldListVO = new RepeatFieldListVO();
            Integer businessType = repeatToolFieldGetDTO.getBusinessType();
            Long formId = repeatToolFieldGetDTO.getFormId();
            String corpid = repeatToolFieldGetDTO.getCorpid();

            List<RepeatFieldPojo> repeatFieldPojoList = new ArrayList<>();
            if (Objects.equals(Integer.valueOf(formId.toString()), BasicConstant.ZERO)) {
                String Attr = CustomerManagementEnum.NAME.getAttr();
                String AttrName = CustomerManagementEnum.NAME.getAttrName();
                String phoneAttr = CustomerManagementEnum.PHONE.getAttr() + ".text_2";
                String phoneAttrName = CustomerManagementEnum.PHONE.getAttrName()+ "("+ClueEnum.PHONE.getAttrName()+")";
                if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())) {
                    Attr = ClueEnum.COMPANY_NAME.getAttr();
                    AttrName = ClueEnum.COMPANY_NAME.getAttrName();
                    phoneAttr = ClueEnum.PHONE.getAttr() + ".text_2";
                    phoneAttrName = ClueEnum.PHONE.getAttrName()+ "("+ClueEnum.PHONE.getAttrName()+")";
                } else if (Objects.equals(businessType,XbbRefTypeEnum.CONTACT.getCode())) {
                    Attr = ContactEnum.NAME.getAttr();
                    AttrName = ContactEnum.NAME.getAttrName();
                    phoneAttr = ContactEnum.PHONE.getAttr() + ".text_2";
                    phoneAttrName = ContactEnum.PHONE.getAttrName()+ "("+ClueEnum.PHONE.getAttrName()+")";
                } else if(Objects.equals(businessType,XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())){
                    Attr = SalesOpportunityEnum.NAME.getAttr();
                    AttrName = SalesOpportunityEnum.NAME.getAttrName();
                }
                RepeatFieldPojo nameRepeatFieldPojo = new RepeatFieldPojo(Attr,AttrName,FieldTypeEnum.TEXT.getType(),"");
                RepeatFieldPojo phoneRepeatFieldPojo = new RepeatFieldPojo(phoneAttr,phoneAttrName,FieldTypeEnum.TEXT.getType(),"");
                repeatFieldPojoList.add(nameRepeatFieldPojo);
                repeatFieldPojoList.add(phoneRepeatFieldPojo);
            } else {
                //高级查重获取查重字段
                PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId, corpid);
                //过滤掉隐藏字段（模板设计页不展示,这里存在坑,比如subForm_2 本身是隐藏的，但是其里面的电话又是非隐藏）
                List<FieldAttrEntity> explainList = JSONArray.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
                explainList.removeIf(item -> (Objects.equals(item.getEditHide(), BasicConstant.ONE) || Objects.equals(item.getFieldType(), FieldTypeEnum.USER.getType()) || Objects.equals(item.getFieldType(), FieldTypeEnum.SERIALNO.getType())));
                Map<String, FieldAttrEntity> explainMap = ExplainUtil.getAllSubFormExplainMap(JSON.toJSONString(explainList));
                for (String fieldAttr : explainMap.keySet()) {
                    FieldAttrEntity fieldAttrEntity = explainMap.get(fieldAttr);
                    if (Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) || Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())) {
                        if (Objects.equals(fieldAttr,"text_1")) {
                            String config = FormConfigEnum.CUSTOMER_NAME_REPEAT_TYPE.getConfig();
                            if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())) {
                                config =FormConfigEnum.CLUE_NAME_REPEAT_TYPE.getConfig();
                            }
                            FormConfigEntity formConfigEntity = formConfigModel.getEntityByFormId(corpid, formId, config);
                            if (formConfigEntity != null) {
                                //由于之前老的数据客户名称、电话没有维护noRepeat，所以需要查配置来判断是否存在。
                                if (!Objects.equals(formConfigEntity.getConfigValue(), RepeatTypeEnum.REPEAT_CANCEL.getType().toString())) {
                                    fieldAttrEntity.setNoRepeat(BasicConstant.ONE);
                                } else {
                                    fieldAttrEntity.setNoRepeat(BasicConstant.ZERO);
                                }
                            }
                        }

                        if (Objects.equals(fieldAttr,"subForm_1.text_2")) {
                            String config = FormConfigEnum.CUSTOMER_PHONE_REPEAT_TYPE.getConfig();
                            if (Objects.equals(businessType,XbbRefTypeEnum.CLUE.getCode())) {
                                config =FormConfigEnum.CLUE_PHONE_REPEAT_TYPE.getConfig();
                            }
                            FormConfigEntity formConfigEntity = formConfigModel.getEntityByFormId(corpid, formId, config);
                            if (formConfigEntity != null) {
                                //由于之前老的数据客户名称、电话没有维护noRepeat，所以需要查配置来判断是否存在。
                                if (!Objects.equals(formConfigEntity.getConfigValue(), RepeatTypeEnum.REPEAT_CANCEL.getType().toString())) {
                                    fieldAttrEntity.setNoRepeat(BasicConstant.ONE);
                                } else {
                                    fieldAttrEntity.setNoRepeat(BasicConstant.ZERO);
                                }
                            }
                        }
                    }

                    if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getIsOpen(),BasicConstant.ONE) && Objects.nonNull(fieldAttrEntity.getNoRepeat()) && Objects.equals(fieldAttrEntity.getNoRepeat(),BasicConstant.ONE)) {
                        RepeatFieldPojo repeatFieldPojo = new RepeatFieldPojo();
                        repeatFieldPojo.setAttr(fieldAttr);
                        if (fieldAttr.contains(StringConstant.POINT)) {
                            String[] split = fieldAttr.split("\\.");
                            if (split !=null && split.length > 0) {
                                FieldAttrEntity parentFieldAttrEntity = explainMap.get(split[0]);
                                if (Objects.equals(parentFieldAttrEntity.getIsOpen(),BasicConstant.ZERO)) {
                                    continue;
                                }
                                repeatFieldPojo.setAttrName(parentFieldAttrEntity.getAttrName() +"(" + fieldAttrEntity.getAttrName() +")");
                            }
                        }else {
                            repeatFieldPojo.setAttrName(fieldAttrEntity.getAttrName());
                        }
                        repeatFieldPojo.setFieldType(fieldAttrEntity.getFieldType());
                        repeatFieldPojo.setValue("");
                        repeatFieldPojoList.add(repeatFieldPojo);
                    }
                }
            }
            repeatFieldListVO.setRepeatFieldList(repeatFieldPojoList);
        } catch (Exception e) {
            LOG.error("getRepeatField查询查重字段数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return repeatFieldListVO;
    }

    /**
     * 这些字段不给合并客户展示
     * @param item
     * @return
     */
    public boolean removeNotShowAttr(FieldAttrEntity item) {
        return Objects.equals(item.getAttr(), CustomerManagementEnum.CREATOR_ID.getAttr())
                || Objects.equals(item.getAttr(), CustomerManagementEnum.ADD_TIME.getAttr())
                    || Objects.equals(item.getAttr(), CustomerManagementEnum.UPDATE_TIME.getAttr())
                        || Objects.equals(item.getAttr(), CustomerManagementEnum.CREATOR.getAttr())
                            || Objects.equals(item.getAttr(), CustomerManagementEnum.LAST_CONNECT_TIME.getAttr())
                                || Objects.equals(item.getAttr(), CustomerManagementEnum.SCORE.getAttr())
                                    || Objects.equals(item.getAttr(), CustomerManagementEnum.CONTACT_PHONE.getAttr())
                || Objects.equals(item.getAttr(), CustomerManagementEnum.CONTACT_NAME.getAttr())
                || Objects.equals(item.getAttr(), CustomerManagementEnum.BACK_PUBLIC_DATE.getAttr())
        ;
    }

    /**
     * 合同关联产品业务选择,选择产品列表
     *
     * @param productListDataDTO 对象
     * @return 产品列表
     * @throws XbbException 抛出业务异常
     */
    @Override
    public PaasFormDataEsListVO getRefundProductlist(ProductListDataDTO productListDataDTO) throws XbbException {
        // jxc开启时:查询退货出库产品  jxc关闭时:查询退货合同产品
        boolean isOpenJxc = refundService.ifJXCOpen(productListDataDTO.getCorpid());
        List<Long> idIn = new ArrayList<>();
        if ( isOpenJxc ) {
            idIn = getRemainProductJxc(productListDataDTO);
        } else {
            idIn = getRemainProductNotJxc(productListDataDTO);
        }
        productListDataDTO.setIdIn(idIn);
        PaasFormDataEsListVO formDataListVO = getProductList(productListDataDTO);
        if ( idIn.isEmpty() ) {
            formDataListVO.setPaasFormDataESList(new ArrayList<>());
            formDataListVO.setPageHelper(new PageHelper());
        }
        return formDataListVO;
    }

    /**
     * 根据查询条件查找对应的es数据
     *
     * @param esDataDTO 封装了查询条件的DTO
     * @author chaoxiong.lei
     * @Date 10:17 2019/2/18
     * @since v1.0
     **/
    @Override
    public PaasFormDataEsListVO getEsDataList(EsDataDTO esDataDTO) throws XbbException {
        return formDataService.getEsDataList(esDataDTO);
    }

    /**
     * 关联业务选择，父业务约束
     *
     * @param businessDataDTO 关联业务参数
     * @param formDataListDTO 列表页查询参数
     */
    private void setParentBusinessType(BusinessDataDTO businessDataDTO, FormDataListDTO formDataListDTO) throws XbbException {
        Integer parentBusinessType = businessDataDTO.getParentBusinessType();
        Long parentId = businessDataDTO.getParentId();
        Integer businessType = businessDataDTO.getBusinessType();
        Integer sourceBusinessType = businessDataDTO.getSourceBusinessType();
        Integer instockType = businessDataDTO.getType();
        if ( parentBusinessType != null && parentBusinessType > 0 && parentId != null && parentId > 0 ) {
            RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
            List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
            if ( conditionList == null ) {
                conditionList = new ArrayList<>();
            }
            String parentAttr = null;
            switch (redundantTemplateTypeEnum) {
                //
                case SALES_OPPORTUNITY:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                        parentAttr = SalesOpportunityEnum.CUSTOMER_NAME.getAttr();
                    } else if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTACT.getCode()) ) {
                        parentAttr = SalesOpportunityEnum.CONTACT_NAME.getAttr();
                    }
                    break;
                case CONTACT:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                        parentAttr = ContactEnum.CUSTOMER_NAME.getAttr();
                    }
                    break;
                case CONTRACT:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                        parentAttr = ContractEnum.LINK_CUSTOMER.getAttr();
                    }
                    break;
                case COMMUNICATE_PLAN:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                        parentAttr = CommunicatePlanEnum.LINK_CUSTOMER.getAttr();
                    }
                    break;
                case PURCHASE:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.SUPPLIER.getCode()) ) {
                        parentAttr = PurchaseEnum.SUPPLIER_ID.getAttr();
                    }
                    break;
                case SUPPLIER_CONTACT:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.SUPPLIER.getCode()) ) {
                        parentAttr = SupplierContactEnum.SUPPLIER_ID.getAttr();
                    }
                    break;
                case PAYMENT:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                        parentAttr = PaymentEnum.CUSTOMER.getAttr();
                    }
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
                        parentAttr = PaymentEnum.CONTRACT.getAttr();
                    }
                    break;
                case INVOICE:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER.getCode()) ) {
                        parentAttr = InvoiceEnum.CUSTOMER_NAME.getAttr();
                    }
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
                        parentAttr = InvoiceEnum.CONTRACT_ID.getAttr();
                    }
                    break;
                case PURCHASE_INVOICE:
                    if(Objects.equals(parentBusinessType,XbbRefTypeEnum.SUPPLIER.getCode())){
                        parentAttr = PurchaseInvoiceEnum.SUPPLIER_NAME.getAttr();
                    }
                    if(Objects.equals(parentBusinessType,XbbRefTypeEnum.PURCHASE.getCode())){
                        parentAttr = PurchaseInvoiceEnum.PURCHASE_ID.getAttr();
                    }
                    break;
                case PAYMENT_SHEET:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
                        parentAttr = PaymentSheetEnum.CONTRACT.getAttr();
                    }
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                        parentAttr = PaymentSheetEnum.CUSTOMER_ID.getAttr();
                    }
                    break;
                case PAY_SHEET:
                    if (Objects.equals(parentBusinessType, XbbRefTypeEnum.PURCHASE.getCode())) {
                        parentAttr = PaySheetEnum.LINK_PURCHASE.getAttr();
                    }
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.SUPPLIER.getCode()) ) {
                        parentAttr = PaySheetEnum.LINK_SUPPLIER.getAttr();
                    }
                    break;
                case PAY_PLAN:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.SUPPLIER.getCode()) ) {
                        parentAttr = PayPlanEnum.LINK_SUPPLIER.getAttr();
                    }
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.PURCHASE.getCode()) ) {
                        parentAttr = PayPlanEnum.LINK_PURCHASE.getAttr();
                    }
                    break;
                case INVENTORY:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.WAREHOUSE.getCode()) ) {
                        parentAttr = InventoryEnum.WAREHOUSE_ID.getAttr();
                    }
                    break;
                case TRANSFER:
                    if (Objects.equals(parentBusinessType, XbbRefTypeEnum.WAREHOUSE.getCode())) {
                        if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())) {
                            parentAttr = TransferEnum.OUT_WAREHOUSE_ID.getAttr();
                        } else if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.OTHER_INSTOCK.getCode())) {
                            parentAttr = TransferEnum.INTO_WAREHOUSE_ID.getAttr();
                        }
                    }
                    break;
                case PRODUCTIONORDER:
                    if (Objects.equals(parentBusinessType, XbbRefTypeEnum.WAREHOUSE.getCode())) {
                        if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.OUTSTOCK.getCode())
                                || Objects.equals(sourceBusinessType,XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode())) {
                            parentAttr = ProductionOrderEnum.OUT_WAREHOUSE_ID.getAttr();
                        } else if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.INSTOCK.getCode())
                                || Objects.equals(sourceBusinessType, XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode())
                                || Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())) {
                            if (Objects.equals(instockType, InstockTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())) {
                                // 退料入库，仓库为出库仓库
                                parentAttr = ProductionOrderEnum.OUT_WAREHOUSE_ID.getAttr();
                            } else {
                                parentAttr = ProductionOrderEnum.INTO_WAREHOUSE_ID.getAttr();
                            }
                        }
                    }
                    break;
                case QUOTATION:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                        parentAttr = QuotationEnum.CUSTOMER_ID.getAttr();
                    } else if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode()) ) {
                        parentAttr = QuotationEnum.OPPORTUNITY_ID.getAttr();
                    }
                    break;
                case REFUND:
                    if (Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                        parentAttr = RefundEnum.CUSTOMER_ID.getAttr();
                    }
                    break;
                case RETURNED_PURCHASE:
                    if (Objects.equals(parentBusinessType, XbbRefTypeEnum.SUPPLIER.getCode())) {
                        parentAttr = ReturnedPurchaseEnum.LINK_SUPPLIER.getAttr();
                    }
                    break;
                case WORKORDER:
//                    if (Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
//                        parentAttr = WorkOrderEnum.LINK_CUSTOMER.getAttr();
//                    }
                    break;
                case PAYMENT_TASK:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
                        parentAttr = PaymentTaskEnum.LINK_CONTRACT.getAttr();
                    }
                    break;
                default:
                    return;
            }
            if ( parentAttr == null ) {
                return;
            }
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(parentAttr);
            conditionsEntityExt.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
            conditionsEntityExt.setName("");
            conditionsEntityExt.setSubAttr("");
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            List<Object> valueList = new ArrayList<>();
            valueList.add(parentId.toString());
            conditionsEntityExt.setValue(valueList);
            conditionList.add(conditionsEntityExt);
            formDataListDTO.setConditions(conditionList);
        } else if ( parentBusinessType != null && parentBusinessType > 0 && parentId == null && CollectionsUtil.isNotEmpty(businessDataDTO.getParentIdList()) ) {
            //可优化代码复用率
            RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
            List<ConditionsEntityExt> conditionList = formDataListDTO.getConditions();
            if ( conditionList == null ) {
                conditionList = new ArrayList<>();
            }
            String parentAttr = null;
            switch (redundantTemplateTypeEnum) {
                case PAYMENT:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                        parentAttr = PaymentEnum.CUSTOMER.getAttr();
                    }
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
                        parentAttr = PaymentEnum.CONTRACT.getAttr();
                    }
                    break;
                case PAYMENT_SHEET:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode()) ) {
                        parentAttr = PaymentSheetEnum.CUSTOMER_ID.getAttr();
                    }
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
                        parentAttr = PaymentSheetEnum.CONTRACT.getAttr();
                    }
                    break;
                case PAY_SHEET:
                    if (Objects.equals(parentBusinessType, XbbRefTypeEnum.PURCHASE.getCode())) {
                        parentAttr = PaySheetEnum.LINK_PURCHASE.getAttr();
                    }
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.SUPPLIER.getCode()) ) {
                        parentAttr = PaySheetEnum.LINK_SUPPLIER.getAttr();
                    }
                    break;
                case PAY_PLAN:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.SUPPLIER.getCode()) ) {
                        parentAttr = PayPlanEnum.LINK_SUPPLIER.getAttr();
                    }
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.PURCHASE.getCode()) ) {
                        parentAttr = PayPlanEnum.LINK_PURCHASE.getAttr();
                    }
                    break;
                case PAYMENT_TASK:
                    if ( Objects.equals(parentBusinessType, XbbRefTypeEnum.CONTRACT.getCode()) ) {
                        parentAttr = PaymentTaskEnum.LINK_CONTRACT.getAttr();
                    }
                    break;
                default:
                    return;
            }
            if ( parentAttr == null ) {
                return;
            }
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(parentAttr);
            conditionsEntityExt.setFieldType(FieldTypeEnum.LINK_BUSINESS_MULTI.getType());
            conditionsEntityExt.setName("");
            conditionsEntityExt.setSubAttr("");
            conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
            List<Object> valueList = new ArrayList<>();
            valueList.addAll(businessDataDTO.getParentIdList());
            conditionsEntityExt.setValue(valueList);
            conditionList.add(conditionsEntityExt);
            formDataListDTO.setConditions(conditionList);
        }
    }

    /**
     * @param businessDataDTO
     * @param formDataListDTO
     * @return void
     * @author chaoxiong.lei
     * @Date 22:13 2019/2/28
     * @since
     **/
    private void specialHandleConditions(BusinessDataDTO businessDataDTO, FormDataListDTO formDataListDTO) throws XbbException {
        Integer businessType = businessDataDTO.getBusinessType();
        Integer sourceBusinessType = businessDataDTO.getSourceBusinessType();
        Integer parentBusinessType = businessDataDTO.getParentBusinessType();
        InvoiceSpecialParamPojo invoiceSpecialParamPojo = businessDataDTO.getInvoiceSpecialParamPojo();
        Integer invoiceLinkContractType = null;
        Long invoiceId = null;
        if (Objects.nonNull(invoiceSpecialParamPojo)){
            //获得关联合同订单界面标识
            invoiceLinkContractType = invoiceSpecialParamPojo.getInvoiceLinkContractType();
            //获得关联合同订单界面的invoiceId
            invoiceId = invoiceSpecialParamPojo.getInvoiceId();
        }
        List<ConditionsEntityExt> conditions = formDataListDTO.getConditions();
        if ( conditions == null ) {
            conditions = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        }
        String corpid = businessDataDTO.getCorpid();
        EsScriptConditionPojo esScriptConditionPojo = new EsScriptConditionPojo();
        EsScriptPojo esScriptPojo = new EsScriptPojo();
        List<EsScriptPojo> esScriptPojoList = new ArrayList<>();
//        if (sourceBusinessType != null && sourceBusinessType > 0) {
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
                ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
                if (!Objects.equals(businessDataDTO.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    conditionsEntityExt.setAttr(CustomerManagementEnum.IS_PUBLIC.getAttr());
                    conditionsEntityExt.setFieldType(CustomerManagementEnum.IS_PUBLIC.getFieldType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Arrays.asList(0));
                    conditions.add(conditionsEntityExt);
                } else {
                    if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.CREDIT_TEMPORARY_LIMIT.getCode()) || Objects.equals(sourceBusinessType, XbbRefTypeEnum.CREDIT_FIXED_LIMIT.getCode())) {
                        // 查询有信用额度的经销商
                        List<CreditLimitEntityExt> distributors = creditLimitService.getCreditDistributors(corpid, businessDataDTO.getDistributorMark(), CreditLimitStatusEnum.NORMAL.getCode());
                        List<Object> distributorIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                        distributors.forEach(item -> distributorIds.add(item.getData().getString(CreditLimitEnum.CUSTOMER_ID.getAttr())));
                        conditionsEntityExt = new ConditionsEntityExt();
                        conditionsEntityExt.setAttr(StringConstant.DATA_ID);
                        conditionsEntityExt.setFieldType(FieldTypeEnum.DATAID.getType());
                        conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                        conditionsEntityExt.setValue(!distributorIds.isEmpty() ? distributorIds : Arrays.asList(-1));
                        conditions.add(conditionsEntityExt);
                    } else if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.CREDIT_LIMIT.getCode())) {
                        conditionsEntityExt = new ConditionsEntityExt();
                        conditionsEntityExt.setAttr(DistributorEnum.PAYMENT_BY_CREDIT.getAttr());
                        conditionsEntityExt.setFieldType(DistributorEnum.PAYMENT_BY_CREDIT.getFieldType());
                        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                        conditionsEntityExt.setValue(Arrays.asList(DistributorCreditStatusEnum.ALLOW.getCode()));
                        conditions.add(conditionsEntityExt);
                    }
                }
                break;
            case INVENTORY:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode())) {
                    // 增加盘亏条件
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(InventoryEnum.IF_LOSS.getAttr());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Arrays.asList(1));
                    conditions.add(conditionsEntityExt);
                    // outstockId为空
                    ConditionsEntityExt outstockIdConditions = new ConditionsEntityExt();
                    outstockIdConditions.setAttr(InventoryEnum.OUTSTOCK_ID.getAttr());
                    outstockIdConditions.setFieldType(InventoryEnum.OUTSTOCK_ID.getFieldType());
                    outstockIdConditions.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    outstockIdConditions.setValue(Arrays.asList(0));
                    conditions.add(outstockIdConditions);
                } else if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.PURCHASE_INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.REFUND_INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.OTHER_INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())) {
                    // 增加盘盈条件
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(InventoryEnum.IF_PROFIT.getAttr());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Arrays.asList(1));
                    conditions.add(conditionsEntityExt);
                    // instockId为空
                    ConditionsEntityExt instockIdConditions = new ConditionsEntityExt();
                    instockIdConditions.setAttr(InventoryEnum.INSTOCK_ID.getAttr());
                    instockIdConditions.setFieldType(InventoryEnum.INSTOCK_ID.getFieldType());
                    instockIdConditions.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    instockIdConditions.setValue(Arrays.asList(0));
                    conditions.add(instockIdConditions);
                }
                break;
            case TRANSFER:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode())) {
                    // 出库单选择调拨单，只能选择没有出库过的调拨单，即出库单为空，或者为0
                    ConditionsEntityExt outstockCondition = new ConditionsEntityExt();
                    outstockCondition.setAttr(TransferEnum.OUTSTOCK_ID.getAttr());
                    outstockCondition.setFieldType(TransferEnum.OUTSTOCK_ID.getFieldType());
                    outstockCondition.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    // 出库单id=0
                    outstockCondition.setValue(Arrays.asList(0));
                    conditions.add(outstockCondition);
                } else if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.PURCHASE_INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.REFUND_INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.OTHER_INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())) {
                    // 入库单选择调拨单，未入库完毕的
                    ConditionsEntityExt outstockIdConditions = new ConditionsEntityExt();
                    outstockIdConditions.setAttr(TransferEnum.ALL_IN_BOUND.getAttr());
                    outstockIdConditions.setFieldType(TransferEnum.ALL_IN_BOUND.getFieldType());
                    outstockIdConditions.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    outstockIdConditions.setValue(Collections.singletonList(0));
                    conditions.add(outstockIdConditions);
                }
                break;
            case CONTRACT:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())) {
                    // 查找的是还没出库完毕的的合同（未开启超发出库时）
//                        if(!companyConfigModel.getOverOutstock(corpid)) {
//                            modelMap.put("allOutbound", 0);
//                        }
//                        if(!userModel.isBoss(userEntity)){
//                            List<String> userIdIn = userModel.getSubIdsByDataPermission(userEntity, 0);
//                            userIdIn.add(userEntity.getUserId());
//                            CommentUtil.addToMap(modelMap, "distinctAndJoin", "distinctAndJoin");
//                            CommentUtil.addToMap(modelMap, "userIdIn", userIdIn);
//                        }
//                        modelMap.put("isRed", 1);
//                        if (!companyConfigService.getOverOutstock(corpid)) {
                    // 查询是否可以超发出库
                    FormConfigEntity overOutstockConfig = formConfigModel.getEntityByFormId(corpid, businessDataDTO.getFormId(), FormConfigEnum.CONTRACT_ALLOW_OUTSTOCK_PRODUCT_NUM_LARGER_SOLD.getConfig());
                    boolean overOutstock = Objects.nonNull(overOutstockConfig) && Objects.equals(overOutstockConfig.getConfigValue(), "1");
                    if (!overOutstock) {
                        EsConditionUtil.allOutBound(conditions, 0);
                    }
                    EsConditionUtil.isRed(conditions, 0);
//                        }

                    ConditionsEntityExt contractConditions = new ConditionsEntityExt();
                    contractConditions.setAttr(ContractEnum.SHIP_STATUS.getAttr());
                    contractConditions.setFieldType(ContractEnum.SHIP_STATUS.getFieldType());
                    contractConditions.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
                    contractConditions.setValue(Collections.singletonList(ShipStatusEnum.CLOSED.getCode()));
                    conditions.add(contractConditions);

                } else if ( Objects.equals(sourceBusinessType, XbbRefTypeEnum.INSTOCK.getCode()) ) {
                    // 入库单选择合同，选择红冲合同
//                        modelMap.put("allOutbound", 0);
//                        modelMap.put("isRed", 1);
                    EsConditionUtil.allOutBound(conditions, 0);
                    EsConditionUtil.isRed(conditions, 1);
                } else if (PaymentSheetTypeEnum.isWriteOffByBusinessType(sourceBusinessType)) {
                    //创建回款单选择合同时，需限制非红冲，且未收金额大于0
                    EsConditionUtil.isRed(conditions, 0);
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(ContractEnum.UN_FINISH_AMOUNT.getAttr());
                    conditionsEntityExt.setFieldType(ContractEnum.UN_FINISH_AMOUNT.getFieldType());
                    conditionsEntityExt.setSymbol(ConditionEnum.GREATERTHAN.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(0));
                    conditions.add(conditionsEntityExt);
                } else if(PaymentSheetTypeEnum.isRedByBusinessType(sourceBusinessType)){
                    //创建回款单选择合同时，需限制非红冲，且已收金额大于0
                    EsConditionUtil.isRed(conditions, 0);
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(ContractEnum.FINISH_AMOUNT.getAttr());
                    conditionsEntityExt.setFieldType(ContractEnum.FINISH_AMOUNT.getFieldType());
                    conditionsEntityExt.setSymbol(ConditionEnum.GREATERTHAN.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(0));
                    conditions.add(conditionsEntityExt);
                } else if(Objects.equals(XbbRefTypeEnum.PAYMENT_TASK.getCode(), sourceBusinessType)){
                    //创建回款计划选择合同时，需限制非红冲，且未收金额大于0
                    EsConditionUtil.isRed(conditions, 0);
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(ContractEnum.UN_FINISH_AMOUNT.getAttr());
                    conditionsEntityExt.setFieldType(ContractEnum.UN_FINISH_AMOUNT.getFieldType());
                    conditionsEntityExt.setSymbol(ConditionEnum.GREATERTHAN.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(0));
                    conditions.add(conditionsEntityExt);
                }else if(Objects.nonNull(invoiceLinkContractType) && Objects.nonNull(invoiceId)&& Objects.equals(BasicConstant.ONE, invoiceLinkContractType)){
                    //是关联合同订单界面，添加只展示合同未开票金额大于开票金额的合同筛选条件
                    InvoiceEntityExt invoiceEntityExt = invoiceModel.getByKey(invoiceId, corpid);
                    //开票金额
                    double invoiceMoney = invoiceEntityExt.getData().getDoubleValue(InvoiceEnum.TOTAL_MONEY.getAttr());
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(ContractEnum.UN_INVOICE_AMOUNT.getAttr());
                    conditionsEntityExt.setFieldType(ContractEnum.UN_INVOICE_AMOUNT.getFieldType());
                    conditionsEntityExt.setSymbol(ConditionEnum.GREATEREQUAL.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(invoiceMoney));
                    conditions.add(conditionsEntityExt);
                }
                else {
                    EsConditionUtil.isRed(conditions, 0);
                }

                if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.INVOICE.getCode())){
                    esScriptPojo.setConditionEnum(ConditionEnum.GREATERTHAN);
                    esScriptPojo.setSourceNeedData(true);
                    esScriptPojo.setTargetNeedData(true);
                    esScriptPojo.setSourceEnum(new EnumBase(ContractEnum.AMOUNT));
                    esScriptPojo.setTargetEnum(new EnumBase(ContractEnum.INVOICE_AMOUNT));
                    esScriptPojoList.add(esScriptPojo);
                    esScriptConditionPojo.setEsScriptList(esScriptPojoList);
                    esScriptConditionPojo.setRelCode(RelTypeEnum.AND.getCode());
                    formDataListDTO.setEsScriptPojo(esScriptConditionPojo);
                }
                break;
            case INVOICE:
                conditionsEntityExt = new ConditionsEntityExt();
                conditionsEntityExt.setAttr(InvoiceEnum.IS_CANCEL.getAttr());
                conditionsEntityExt.setFieldType(InvoiceEnum.IS_CANCEL.getFieldType());
                conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                conditionsEntityExt.setValue(Collections.singletonList(0));
                conditions.add(conditionsEntityExt);
                break;
            case PURCHASE_INVOICE:
                conditionsEntityExt = new ConditionsEntityExt();
                conditionsEntityExt.setAttr(PurchaseInvoiceEnum.IS_CANCEL.getAttr());
                conditionsEntityExt.setFieldType(PurchaseInvoiceEnum.IS_CANCEL.getFieldType());
                conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                conditionsEntityExt.setValue(Collections.singletonList(0));
                conditions.add(conditionsEntityExt);
                break;
            case PAYMENT:
                conditionsEntityExt = new ConditionsEntityExt();
                conditionsEntityExt.setAttr(PaymentEnum.IS_RED.getAttr());
                conditionsEntityExt.setFieldType(PaymentEnum.IS_RED.getFieldType());
                conditionsEntityExt.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
                conditionsEntityExt.setValue(Collections.singletonList(1));
                conditions.add(conditionsEntityExt);
                //只能读取非红冲的应收款
                conditions.add(new ConditionsEntityExt(PaymentEnum.RECEIVABLE_IS_RED.getAttr(), "",PaymentEnum.RECEIVABLE_IS_RED.getFieldType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(1)));
                if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.INVOICE.getCode())){
                    conditions.add(new ConditionsEntityExt(PaymentEnum.STATUS.getAttr(), "",PaymentEnum.STATUS.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(PaymentStatusEnum.UN_RECEIVABLES.getCode(),PaymentStatusEnum.RECEIVABLES.getCode(),PaymentStatusEnum.PARTIAL_RECEIPTS.getCode())));
                    //发票只能选择非模式二的应收款（因为模式二时基于开票生成的数据）
                    conditions.add(new ConditionsEntityExt(FieldTypeEnum.SYS_LONG_10.getAlias(), "", FieldTypeEnum.SYS_LONG_10.getType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(ModelTypeEnum.INVOICE.getCode())));
                    esScriptPojo.setConditionEnum(ConditionEnum.GREATERTHAN);
                    esScriptPojo.setSourceNeedData(true);
                    esScriptPojo.setTargetNeedData(true);
                    esScriptPojo.setSourceEnum(new EnumBase(PaymentEnum.AMOUNT));
                    esScriptPojo.setTargetEnum(new EnumBase(PaymentEnum.INVOICE_AMOUNT));
                    esScriptPojoList.add(esScriptPojo);
                    esScriptConditionPojo.setEsScriptList(esScriptPojoList);
                    esScriptConditionPojo.setRelCode(RelTypeEnum.AND.getCode());
                    formDataListDTO.setEsScriptPojo(esScriptConditionPojo);
                } else if (Objects.equals(sourceBusinessType,XbbRefTypeEnum.REFUND.getCode())) {
                    //有未收金额的应收款，如果没有应收款或者应收款的未收金额都为0，则不能选择到应收款。因为创建红冲应收款时要把原应收款的未收款减少
                    conditions.add(new ConditionsEntityExt(PaymentEnum.UN_AMOUNT.getAttr(), "", PaymentEnum.UN_AMOUNT.getFieldType(), ConditionEnum.GREATERTHAN.getSymbol(), Collections.singletonList(BasicConstant.ZERO_DOUBLE)));
                    conditions.add(new ConditionsEntityExt(PaymentEnum.STATUS.getAttr(), "", PaymentEnum.STATUS.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(PaymentStatusEnum.UN_RECEIVABLES.getCode(), PaymentStatusEnum.PARTIAL_RECEIPTS.getCode())));
                }
                break;
            case PAYMENT_SHEET:
                if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.INVOICE.getCode())){
                    //发票只能选择非模式二的回款单（因为模式二时基于开票生成的数据）
                    conditions.add(new ConditionsEntityExt(FieldTypeEnum.SYS_LONG_10.getAlias(), "",FieldTypeEnum.SYS_LONG_10.getType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(ModelTypeEnum.INVOICE.getCode())));
                    if(Objects.equals(parentBusinessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                        //只查预收款
                        conditions.add(new ConditionsEntityExt(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), "", PaymentSheetEnum.PAYMENT_SHEET_TYPE.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetTypeEnum.PREPAYMENT.getCode())));
                        //只查询父单
                        conditions.add(new ConditionsEntityExt(FieldTypeEnum.SHEET_ALONE.getAlias(), "", FieldTypeEnum.SHEET_ALONE.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetAloneEnum.NORMAL.getCode())));
                        // 过虑num_1不存在的数据
                        ConditionsEntityExt conditionsEntity = new ConditionsEntityExt();
                        conditionsEntity.setAttr(PaymentSheetEnum.AMOUNT.getAttr());
                        conditionsEntity.setFieldType(PaymentSheetEnum.AMOUNT.getFieldType());
                        conditionsEntity.setSymbol(ConditionEnum.NOEMPTY.getSymbol());
                        // conditionsEntity.setValue(new ArrayList<>());
                        conditions.add(conditionsEntity);
                        // es版本升级后对script中的字段作了校验，此处兼容回款单中开票金额(num_8)字段不存在的情况, 兼容 num_1 = 0 的情况
                        String esSourceStr = "(doc['data." + PaymentSheetEnum.INVOICE_AMOUNT.getAttr() + "'].size() == 0 && doc['data." + PaymentSheetEnum.AMOUNT.getAttr() +"'].size() != 0 && doc['data." + PaymentSheetEnum.AMOUNT.getAttr() + "'].value > 0) || (doc['data." + PaymentSheetEnum.INVOICE_AMOUNT.getAttr() + "'].size() != 0 && doc['data." + PaymentSheetEnum.AMOUNT.getAttr() + "'].size() != 0 && (doc['data." + PaymentSheetEnum.AMOUNT.getAttr() + "'].value - doc['data." + PaymentSheetEnum.INVOICE_AMOUNT.getAttr() + "'].value > 0))";
                        formDataListDTO.setEsScriptSourceStr(esSourceStr);
                    }else {
                        //筛选条件已核销、核销预付款
                        conditions.add(new ConditionsEntityExt(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), "", PaymentSheetEnum.PAYMENT_SHEET_TYPE.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetTypeEnum.WRITE_OFF.getCode())));
                        //只查询父单
                        conditions.add(new ConditionsEntityExt(FieldTypeEnum.SHEET_ALONE.getAlias(), "", FieldTypeEnum.SHEET_ALONE.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetAloneEnum.NORMAL.getCode(), SheetAloneEnum.CHILD.getCode())));
                        // 过虑num_7不存在的数据
                        ConditionsEntityExt conditionsEntity = new ConditionsEntityExt();
                        conditionsEntity.setAttr(PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr());
                        conditionsEntity.setFieldType(PaymentSheetEnum.WRITE_OFF_AMOUNT.getFieldType());
                        conditionsEntity.setSymbol(ConditionEnum.NOEMPTY.getSymbol());
                        // conditionsEntity.setValue(new ArrayList<>());
                        conditions.add(conditionsEntity);
                        // es版本升级后对script中的字段作了校验，此处兼容回款单中开票金额(num_8)字段不存在的情况, 兼容 num_7 = 0 的情况
                        String esSourceStr = "(doc['data." + PaymentSheetEnum.INVOICE_AMOUNT.getAttr() + "'].size() == 0 && doc['data." + PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr() +"'].size() != 0 && doc['data." + PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr() + "'].value > 0) || (doc['data." + PaymentSheetEnum.INVOICE_AMOUNT.getAttr() + "'].size() != 0 && doc['data." + PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr() + "'].size() != 0 && (doc['data." + PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr() + "'].value - doc['data." + PaymentSheetEnum.INVOICE_AMOUNT.getAttr() + "'].value > 0))";
                        formDataListDTO.setEsScriptSourceStr(esSourceStr);
                    }
                }else if (Objects.equals(sourceBusinessType,XbbRefTypeEnum.PAYMENT.getCode())) {
                    Long dataId = businessDataDTO.getDataId();
                    if (Objects.isNull(dataId)) {
                        throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208071, PaymentErrorCodeEnum.API_ERROR_208071.getMsg());
                    }
                    PaymentEntityExt paymentEntityExt = paymentModel.getByKey(dataId, corpid);
                    if (Objects.isNull(paymentEntityExt)) {
                        throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208077, PaymentErrorCodeEnum.API_ERROR_208077.getMsg());
                    }
                    JSONObject paymentData = JsonHelperUtil.getJSONObject(paymentEntityExt.getData());
                    //有未收才能核销
                    double unAmount = paymentData.getDoubleValue(PaymentBaseEnum.UN_AMOUNT.getAttr());
                    //限制核销金额大于unAmount  （预收款核销和已核销共有的字段是核销金额）
                    conditions.add(new ConditionsEntityExt(PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr(), "", PaymentSheetEnum.WRITE_OFF_AMOUNT.getFieldType(), ConditionEnum.LESSEQUAL.getSymbol(), Arrays.asList(unAmount)));

                    //筛选条件已核销、预收款核销
                    conditions.add(new ConditionsEntityExt(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), "", PaymentSheetEnum.PAYMENT_SHEET_TYPE.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetTypeEnum.WRITE_OFF.getCode(), SheetTypeEnum.WRITE_OFF_PREPAYMENT.getCode())));
                    //只查询父单
                    conditions.add(new ConditionsEntityExt(FieldTypeEnum.SHEET_ALONE.getAlias(), "", FieldTypeEnum.SHEET_ALONE.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetAloneEnum.NORMAL.getCode(), SheetAloneEnum.CHILD.getCode())));
                    // 过虑关联应收款为空的回款单
                    ConditionsEntityExt conditionsEntity = new ConditionsEntityExt();
                    conditionsEntity.setAttr(PaymentSheetEnum.PAYMENT.getAttr());
                    conditionsEntity.setFieldType(PaymentSheetEnum.PAYMENT.getFieldType());
                    conditionsEntity.setSymbol(ConditionEnum.EMPTY.getSymbol());
                    conditions.add(conditionsEntity);
                }else {
                    conditions.add(new ConditionsEntityExt(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), "", PaymentSheetEnum.PAYMENT_SHEET_TYPE.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetTypeEnum.WRITE_OFF.getCode(), SheetTypeEnum.WRITE_OFF_PREPAYMENT.getCode())));
                    ConditionsEntityExt conditionsEntity = new ConditionsEntityExt();
                    conditionsEntity.setAttr(FieldTypeEnum.SHEET_ALONE.getAlias());
                    conditionsEntity.setFieldType(FieldTypeEnum.SHEET_ALONE.getType());
                    conditionsEntity.setSymbol(ConditionEnum.IN.getSymbol());
                    conditionsEntity.setValue(Arrays.asList(SheetAloneEnum.NORMAL.getCode(), SheetAloneEnum.PARENT.getCode()));
                    conditions.add(conditionsEntity);
                }
                break;
            case PURCHASE:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.PURCHASE_INSTOCK.getCode())) {
                    // 表明查找的是还没入库完毕的的采购单
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(PurchaseEnum.ALL_INCOMING.getAttr());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Arrays.asList(0));
                    conditions.add(conditionsEntityExt);
                    ConditionsEntityExt purchaseCondition = new ConditionsEntityExt();
                    purchaseCondition.setAttr(PurchaseEnum.RECEIVE_STATUS.getAttr());
                    purchaseCondition.setFieldType(PurchaseEnum.RECEIVE_STATUS.getFieldType());
                    purchaseCondition.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
                    purchaseCondition.setValue(Arrays.asList(ReceiveStatusEnum.CLOSED.getCode()));
                    conditions.add(purchaseCondition);
                } else if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_PURCHASE.getCode())) {
                    // 表明查找的是已经入过库的的采购合同
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(PurchaseEnum.INSTOCK_ID.getAttr());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.CHECKBOX_GROUP.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.NOEMPTY.getSymbol());
                    conditions.add(conditionsEntityExt);

                    ConditionsEntityExt returnedPurchaseConditions = new ConditionsEntityExt();
                    returnedPurchaseConditions.setAttr(PurchaseEnum.RETURNED_PURCHASE_ID.getAttr());
                    returnedPurchaseConditions.setFieldType(PurchaseEnum.RETURNED_PURCHASE_ID.getFieldType());
                    returnedPurchaseConditions.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    returnedPurchaseConditions.setValue(Collections.singletonList(0));
                    conditions.add(returnedPurchaseConditions);
                } else if (PaySheetTypeEnum.isWriteOffByBusinessType(sourceBusinessType)) {
                    //创建付款单选择采购合同时，且未收金额大于0
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(PurchaseEnum.UN_FINISH_AMOUNT.getAttr());
                    conditionsEntityExt.setFieldType(PurchaseEnum.UN_FINISH_AMOUNT.getFieldType());
                    conditionsEntityExt.setSymbol(ConditionEnum.GREATERTHAN.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(0));
                    conditions.add(conditionsEntityExt);
                } else if(PaySheetTypeEnum.isRedByBusinessType(sourceBusinessType)){
                    //创建红冲付款单选择采购合同时，且已收金额大于0
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(PurchaseEnum.FINISH_AMOUNT.getAttr());
                    conditionsEntityExt.setFieldType(PurchaseEnum.FINISH_AMOUNT.getFieldType());
                    conditionsEntityExt.setSymbol(ConditionEnum.GREATERTHAN.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(0));
                    conditions.add(conditionsEntityExt);
                }
                if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                    esScriptPojo.setConditionEnum(ConditionEnum.GREATERTHAN);
                    esScriptPojo.setSourceNeedData(true);
                    esScriptPojo.setTargetNeedData(true);
                    esScriptPojo.setSourceEnum(new EnumBase(PurchaseEnum.TOTAL_MONEY));
                    esScriptPojo.setTargetEnum(new EnumBase(PurchaseEnum.INVOICE_AMOUNT));
                    esScriptPojoList.add(esScriptPojo);
                    esScriptConditionPojo.setEsScriptList(esScriptPojoList);
                    esScriptConditionPojo.setRelCode(RelTypeEnum.AND.getCode());
                    formDataListDTO.setEsScriptPojo(esScriptConditionPojo);
                }
                break;
            case RETURNED_PURCHASE:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_PURCHASE_OUTSTOCK.getCode())) {
                    // 查找没有出过库的采购退货单
                    // 搜索出库单id为空的数据，因为存储的时候没有默认其为0，所以没有出过库的采购退货单的出库单id为空
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(ReturnedPurchaseEnum.OUTSTOCK_ID.getAttr());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.TEXT.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EMPTY.getSymbol());
                    //conditionsEntityExt.setValue(Collections.singletonList(0));
                    ConditionsEntityExt returnedPurchaseConditions = new ConditionsEntityExt();
                    returnedPurchaseConditions.setAttr(ReturnedPurchaseEnum.RETURNED_STATUS.getAttr());
                    returnedPurchaseConditions.setFieldType(ReturnedPurchaseEnum.RETURNED_STATUS.getFieldType());
                    returnedPurchaseConditions.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
                    returnedPurchaseConditions.setValue(Collections.singletonList(ReturnedStatusEnum.CLOSED.getAttr()));
                    conditions.add(returnedPurchaseConditions);
                    conditions.add(conditionsEntityExt);
                }
                break;
            case PRODUCTIONORDER:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.PRODUCTION_MATERIEL_OUTSTOCK.getCode())) {
                    // 只有未完成状态才可以物料出库
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(ProductionOrderEnum.STATUS.getAttr());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Arrays.asList(1));
                    conditions.add(conditionsEntityExt);
                } else if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.PRODUCTION_INSTOCK.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())) {
                    // 入库单选择生产单，成品入库和退料入库
                    if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.RETURNED_MATERIEL_INSTOCK.getCode())) {
                        // 退料入库
                        conditionsEntityExt = new ConditionsEntityExt();
                        conditionsEntityExt.setAttr(ProductionOrderEnum.HAS_RETURNED_MATERIEL.getAttr());
                        conditionsEntityExt.setFieldType(FieldTypeEnum.NUM.getType());
                        conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                        conditionsEntityExt.setValue(Arrays.asList(1));
                        conditions.add(conditionsEntityExt);
                    }
                    // 未完成和已关闭状态可以退料入库
                    ConditionsEntityExt statusConditions = new ConditionsEntityExt();
                    statusConditions.setAttr(ProductionOrderEnum.STATUS.getAttr());
                    statusConditions.setFieldType(FieldTypeEnum.NUM.getType());
                    statusConditions.setSymbol(ConditionEnum.IN.getSymbol());
                    statusConditions.setValue(Arrays.asList(1, 3));
                    conditions.add(statusConditions);
                }
                break;
            case REFUND:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.REFUND_INSTOCK.getCode())) {
                    // 入库单选择合同，选择退货退款合同(只查询部分(未)入库)
                    EsConditionUtil.allInBound(conditions, BasicConstant.ZERO);
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(RefundEnum.REFUND_STATUS.getAttr());
                    conditionsEntityExt.setFieldType(RefundEnum.REFUND_STATUS.getFieldType());
                    conditionsEntityExt.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(RefundStatusEnum.CLOSED.getCode()));
                    conditions.add(conditionsEntityExt);
                }
                break;
            case WORKORDER:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.WORK_ORDER_OUTSTOCK.getCode())) {
                    //工单出库只查询未完全出库的工单
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(WorkOrderEnum.ALL_OUTBOUND.getAttr());
                    conditionsEntityExt.setFieldType(FieldTypeEnum.WORK_ORDER_ALL_OUTBOUND.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntityExt.setValue(Collections.singletonList(0));
                    conditions.add(conditionsEntityExt);
                    ConditionsEntityExt conditionsEntityExt1 = new ConditionsEntityExt();
                    conditionsEntityExt1.setAttr(WorkOrderEnum.SPARE_PARTS.getAttr());
                    conditionsEntityExt1.setFieldType(FieldTypeEnum.SELECT_PRODUCT.getType());
                    conditionsEntityExt1.setSymbol(ConditionEnum.NOEMPTY.getSymbol());
                    conditions.add(conditionsEntityExt1);
                }
                break;
            case COMMUNICATE_PLAN:
                //只查询未完成的访客计划，并且执行日期在今天，执行人为当前操作人,raolong
                conditionsEntityExt = new ConditionsEntityExt();
                conditionsEntityExt.setAttr(CommunicatePlanEnum.STATUS.getAttr());
                conditionsEntityExt.setFieldType(CommunicatePlanEnum.STATUS.getFieldType());
                conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                conditionsEntityExt.setValue(Arrays.asList(CommunicatePlanStatusEnum.NO_FOLLOW.getCode(), CommunicatePlanStatusEnum.DELAY.getCode()));
                conditions.add(conditionsEntityExt);
/*
                ConditionsEntityExt timeCondition = new ConditionsEntityExt();
                timeCondition.setAttr(CommunicatePlanEnum.COMMUNICATE_TIME.getAttr());
                timeCondition.setSymbol(ConditionEnum.RANGE.getSymbol());
                timeCondition.setValue(Arrays.asList(DateTimeUtil.getTodayInt(), DateTimeUtil.getTodayInt() + 86400));
                timeCondition.setFieldType(CommunicatePlanEnum.COMMUNICATE_TIME.getFieldType());
                conditions.add(timeCondition);*/

                List<Long> dataIdList = communicatePlanUserModel.getDataIdList(corpid, Collections.singletonList(businessDataDTO.getUserId()));
                conditions.add(new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(), "", FieldTypeEnum.DATAID.getType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(dataIdList)));
                Map<String, String> sortMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                sortMap.put("field", CommunicatePlanEnum.COMMUNICATE_TIME.getAttr());
                sortMap.put("sort", SortOrder.ASC.toString());
                formDataListDTO.setSortMap(sortMap);
                break;
            case QUOTATION:
                // 查询最新版本
                conditionsEntityExt = new ConditionsEntityExt();
                conditionsEntityExt.setAttr(QuotationEnum.IS_NEW.getAttr());
                conditionsEntityExt.setFieldType(QuotationEnum.IS_NEW.getFieldType());
                conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                conditionsEntityExt.setValue(Collections.singletonList(BasicConstant.ONE));
                conditions.add(conditionsEntityExt);
                break;
            case PAY_SHEET:
                if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                    if(Objects.equals(parentBusinessType,XbbRefTypeEnum.SUPPLIER.getCode())){
                        conditions.add(new ConditionsEntityExt(PaySheetEnum.PAY_SHEET_TYPE.getAttr(), "", PaySheetEnum.PAY_SHEET_TYPE.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(PaySheetTypeEnum.PREPAY.getCode())));
                        //只查询父单
                        conditions.add(new ConditionsEntityExt(FieldTypeEnum.SHEET_ALONE.getAlias(), "", FieldTypeEnum.SHEET_ALONE.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetAloneEnum.NORMAL.getCode())));
                        // 过虑num_1不存在的数据
                        ConditionsEntityExt conditionsEntity = new ConditionsEntityExt();
                        conditionsEntity.setAttr(PaySheetEnum.AMOUNT.getAttr());
                        conditionsEntity.setFieldType(PaySheetEnum.AMOUNT.getFieldType());
                        conditionsEntity.setSymbol(ConditionEnum.NOEMPTY.getSymbol());
                        // conditionsEntity.setValue(new ArrayList<>());
                        conditions.add(conditionsEntity);
                        // es版本升级后对script中的字段作了校验，此处兼容回款单中开票金额(num_8)字段不存在的情况, 兼容 num_1 = 0 的情况
                        String esSourceStr = "(doc['data." + PaySheetEnum.INVOICE_AMOUNT.getAttr() + "'].size() == 0 && doc['data." + PaySheetEnum.AMOUNT.getAttr() +"'].size() != 0 && doc['data." + PaySheetEnum.AMOUNT.getAttr() + "'].value > 0) || (doc['data." + PaySheetEnum.INVOICE_AMOUNT.getAttr() + "'].size() != 0 && doc['data." + PaySheetEnum.AMOUNT.getAttr() + "'].size() != 0 && (doc['data." + PaySheetEnum.AMOUNT.getAttr() + "'].value - doc['data." + PaySheetEnum.INVOICE_AMOUNT.getAttr() + "'].value > 0))";
                        formDataListDTO.setEsScriptSourceStr(esSourceStr);
                    }else {
                        //筛选条件已核销、核销预付款
                        conditions.add(new ConditionsEntityExt(PaySheetEnum.PAY_SHEET_TYPE.getAttr(), "", PaySheetEnum.PAY_SHEET_TYPE.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(PaySheetTypeEnum.WRITE_OFF_PAY.getCode())));
                        //只查询父单
                        conditions.add(new ConditionsEntityExt(FieldTypeEnum.SHEET_ALONE.getAlias(), "", FieldTypeEnum.SHEET_ALONE.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetAloneEnum.NORMAL.getCode(), SheetAloneEnum.CHILD.getCode())));
                        // 过虑num_2不存在的数据
                        ConditionsEntityExt conditionsEntity = new ConditionsEntityExt();
                        conditionsEntity.setAttr(PaySheetEnum.WRITE_OFF_AMOUNT.getAttr());
                        conditionsEntity.setFieldType(PaySheetEnum.WRITE_OFF_AMOUNT.getFieldType());
                        conditionsEntity.setSymbol(ConditionEnum.NOEMPTY.getSymbol());
                        // conditionsEntity.setValue(new ArrayList<>());
                        conditions.add(conditionsEntity);
                        // es版本升级后对script中的字段作了校验，此处兼容回款单中开票金额(num_3)字段不存在的情况, 兼容 num_2 = 0 的情况
                        String esSourceStr = "(doc['data." + PaySheetEnum.INVOICE_AMOUNT.getAttr() + "'].size() == 0 && doc['data." + PaySheetEnum.WRITE_OFF_AMOUNT.getAttr() +"'].size() != 0 && doc['data." + PaySheetEnum.WRITE_OFF_AMOUNT.getAttr() + "'].value > 0) || (doc['data." + PaySheetEnum.INVOICE_AMOUNT.getAttr() + "'].size() != 0 && doc['data." + PaySheetEnum.WRITE_OFF_AMOUNT.getAttr() + "'].size() != 0 && (doc['data." + PaySheetEnum.WRITE_OFF_AMOUNT.getAttr() + "'].value - doc['data." + PaySheetEnum.INVOICE_AMOUNT.getAttr() + "'].value > 0))";
                        formDataListDTO.setEsScriptSourceStr(esSourceStr);
                    }
                }else {
                    //筛选条件已核销、核销预付款
                    conditions.add(new ConditionsEntityExt(PaySheetEnum.PAY_SHEET_TYPE.getAttr(), "", PaySheetEnum.PAY_SHEET_TYPE.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(PaySheetTypeEnum.WRITE_OFF_PAY.getCode(), PaySheetTypeEnum.WRITE_OFF_PREPAY.getCode())));
                    //只查询父单
                    conditions.add(new ConditionsEntityExt(FieldTypeEnum.SHEET_ALONE.getAlias(), "", FieldTypeEnum.SHEET_ALONE.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(SheetAloneEnum.NORMAL.getCode(), SheetAloneEnum.PARENT.getCode())));
                }
                break;
            case PAY_PLAN:
                if(Objects.equals(sourceBusinessType,XbbRefTypeEnum.PURCHASE_INVOICE.getCode())){
                    conditions.add(new ConditionsEntityExt(PayPlanEnum.STATUS.getAttr(), "",PayPlanEnum.STATUS.getFieldType(), ConditionEnum.IN.getSymbol(), Arrays.asList(PayPlanStatusEnum.UN_RECEIVABLES.getCode(),PayPlanStatusEnum.RECEIVABLES.getCode(),PayPlanStatusEnum.PARTIAL_RECEIPTS.getCode())));
                    esScriptPojo.setConditionEnum(ConditionEnum.GREATERTHAN);
                    esScriptPojo.setSourceNeedData(true);
                    esScriptPojo.setTargetNeedData(true);
                    esScriptPojo.setSourceEnum(new EnumBase(PayPlanEnum.AMOUNT));
                    esScriptPojo.setTargetEnum(new EnumBase(PayPlanEnum.INVOICE_AMOUNT));
                    esScriptPojoList.add(esScriptPojo);
                    esScriptConditionPojo.setEsScriptList(esScriptPojoList);
                    esScriptConditionPojo.setRelCode(RelTypeEnum.AND.getCode());
                    formDataListDTO.setEsScriptPojo(esScriptConditionPojo);
                }
                break;
            case PAYMENT_TASK:
                if (Objects.equals(sourceBusinessType, XbbRefTypeEnum.PAYMENT_SHEET.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.WRITE_OFF_PREPAYMENT.getCode())
                        || Objects.equals(sourceBusinessType, XbbRefTypeEnum.BAD_DEBT.getCode())) {
                    //只读取未完成的回款计划
                    ConditionsEntityExt conditionsEntity = new ConditionsEntityExt();
                    conditionsEntity.setAttr(PaymentTaskEnum.STATUS.getAttr());
                    conditionsEntity.setFieldType(PaymentTaskEnum.STATUS.getFieldType());
                    conditionsEntity.setSymbol(ConditionEnum.EQUAL.getSymbol());
                    conditionsEntity.setValue(Collections.singletonList(PaymentTaskStatusEnum.NO_FINISH.getCode()));
                    conditions.add(conditionsEntity);
                    Map<String, String> sortTaskMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    sortTaskMap.put("field", PaymentTaskEnum.EXECUTOR_TIME.getAttr());
                    sortTaskMap.put("sort", SortOrder.ASC.toString());
                    formDataListDTO.setSortMap(sortTaskMap);
                }
                break;
            case CLUE:
                if (Objects.equals(businessDataDTO.getSourceBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                    ConditionsEntityExt clueCondition = new ConditionsEntityExt();
                    clueCondition.setAttr(ClueEnum.CLUE_STATUS.getAttr());
                    clueCondition.setFieldType(ClueEnum.CLUE_STATUS.getFieldType());
                    clueCondition.setSymbol(ConditionEnum.IN.getSymbol());
                    clueCondition.setValue(Arrays.asList(ClueStatusEnum.PENDING.getCode(), ClueStatusEnum.FOLLOWING_UP.getCode()));
                    conditions.add(clueCondition);
                } else {
                    ConditionsEntityExt clueCondition = new ConditionsEntityExt();
                    clueCondition.setAttr(ClueEnum.IS_PUBLIC.getAttr());
                    clueCondition.setFieldType(ClueEnum.IS_PUBLIC.getFieldType());
                    clueCondition.setSymbol(ConditionEnum.IN.getSymbol());
                    clueCondition.setValue(Arrays.asList());
                    conditions.add(clueCondition);
                }
                break;
            case COMPETITOR:
                if (Objects.equals(businessDataDTO.getSourceBusinessType(), XbbRefTypeEnum.SALES_OPPORTUNITY.getCode())) {
                    Long dataId = businessDataDTO.getDataId();
                    if (Objects.isNull(dataId)) {
                        break;
                    }
                    JSONArray jsonArray = null;
                    OpportunityEntityExt opportunityEntityExt = opportunityModel.getByKey(dataId,corpid);
                    if(opportunityEntityExt!=null){
                        JSONObject data = opportunityEntityExt.getData();
                        jsonArray = data.getJSONArray(SalesOpportunityEnum.LINK_COMPETITOR.getAttr());
                    }
                    conditionsEntityExt = new ConditionsEntityExt();
                    conditionsEntityExt.setAttr(StringConstant.DATA_ID);
                    conditionsEntityExt.setFieldType(FieldTypeEnum.DATAID.getType());
                    conditionsEntityExt.setSymbol(ConditionEnum.IN.getSymbol());
                    conditionsEntityExt.setValue(CollectionsUtil.isNotEmpty(jsonArray)? jsonArray : Arrays.asList(-1));
                    conditions.add(conditionsEntityExt);
                }
                break;
            default:
                break;
        }
        formDataListDTO.setConditions(conditions);
    }


    @Override
    public FormDataDetailVO getDetail(FormDataDetailDTO formDataDetailDTO) throws XbbException {
        BusinessDetailTopInfoService businessDetailTopInfoService = businessDetailTopInfoMap.get(formDataDetailDTO.getBusinessType());
        if (Objects.nonNull(businessDetailTopInfoService) && !Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(), formDataDetailDTO.getDistributorMark())) {
            // 经销商不走这个方法
            return businessDetailTopInfoService.getDetail(formDataDetailDTO);
        }
        if ( Objects.equals(formDataDetailDTO.getBusinessType(), XbbRefTypeEnum.PREPAYMENT_BALANCE.getCode()) ) {
            return paymentBalanceService.getWebDetail(formDataDetailDTO);
        }
        if ( Objects.equals(formDataDetailDTO.getBusinessType(), XbbRefTypeEnum.PREPAY_BALANCE.getCode()) ) {
            return payBalanceService.getWebDetail(formDataDetailDTO);
        }
        if ( Objects.equals(formDataDetailDTO.getBusinessType(), XbbRefTypeEnum.MARKETING_ACTIVITY_MANAGEMENT.getCode()) || Objects.equals(formDataDetailDTO.getBusinessType(), XbbRefTypeEnum.PROMOTION_ACTIVITY_MANAGEMENT.getCode()) ) {
            return marketingManagementService.getWebDetail(formDataDetailDTO);
        }
        //知识库条目详情
        if ( Objects.equals(formDataDetailDTO.getBusinessType(), XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())) {
            return knowledgeDataService.getWebDetail(formDataDetailDTO);
        }
        /*if ( Objects.equals(formDataDetailDTO.getBusinessType(), XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode()) ) {
            return distributorAccountService.getWebDetail(formDataDetailDTO);
        }*/
        if ( Objects.equals(formDataDetailDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) ) {
            // 产品编辑的时候一定要传父产品的id
            PaasFormDataEntityExt productEntity = saasGetHelp.getFormData(formDataDetailDTO.getDataId(), formDataDetailDTO.getCorpid(), XbbRefTypeEnum.PRODUCT.getCode());
            if ( productEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            JSONObject productData = productEntity.getData();
            Long parentId = productData.getLong(ProductEnum.PARENT_ID.getAttr());
            if ( !Objects.equals(parentId, 0L) ) {
                formDataDetailDTO.setDataId(parentId);
            }
        }
        FormDataDetailVO formDataDetailVO = new FormDataDetailVO();
        String userId = formDataDetailDTO.getUserId();
        //判断老搜客能否使用
        SearchCustomerCompanyEntity byCorpid = searchCustomerCompanyModel.getByCorpid(formDataDetailDTO.getCorpid(), SoukeMealEnum.SOUKE.getType());
        if (Objects.nonNull(byCorpid) && byCorpid.getExtraExpiry() > DateUtil.getInt()){
            formDataDetailVO.setIsBusiness(1);
        }
        //判断工商查询能否使用
        if (fineClueHelp.isFineClueByCorpid(formDataDetailDTO.getCorpid(), formDataDetailDTO.getBusinessType(), formDataDetailDTO.getDistributorMark())) {
            formDataDetailVO.setIsFineClue(1);
        }

        // 子表单
        try {
            List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
            List<ButtonPojo> buttonPojoList = new ArrayList<>();
            DetailTitlePojo titlePojo = new DetailTitlePojo();
            DataDetailPojo dataDetailPojo = new DataDetailPojo();
            String corpid = formDataDetailDTO.getCorpid();
            Integer saasMark = formDataDetailDTO.getSaasMark();
            Long dataId = formDataDetailDTO.getDataId();
            Long menuId = formDataDetailDTO.getMenuId();
            Long appId = null;
            Long formId;
            PaasFormDataEntityExt paasFormDataEntityExt;
            Integer distributorMark = formDataDetailDTO.getDistributorMark();
            if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                Integer businessType = XbbRefTypeEnum.transferBusinessType4Distributor(formDataDetailDTO.getBusinessType(), distributorMark);
                formDataDetailDTO.setBusinessType(businessType);
                formDataDetailDTO.setSubBusinessType(businessType);
            }
            Integer businessType = formDataDetailDTO.getBusinessType();
            Integer subBusinessType = formDataDetailDTO.getSubBusinessType();
            UserVO loginUser = formDataDetailDTO.getLoginUser();
            // 详情标签、摘要(按顺序返回给前端)
            JSONArray secondTitle = new JSONArray();
            // 标签
            JSONArray tags = new JSONArray();
            SheetTypeEnum sheetTypeEnum = SheetTypeEnum.getByBusinessType(businessType);
            boolean sheetFlag = SheetTypeEnum.validateSheet(sheetTypeEnum);
            //标签解释字段
            FieldAttrEntity labelField = null;
            HandelDetailPojo handelDetailPojo = new HandelDetailPojo();
            HandlerExplainDTO handlerExplainDTO;
            if ( SaasMarkEnum.SAAS.getCode().equals(saasMark) ) {
                if ( sheetFlag ) {
                    paasFormDataEntityExt = proGetHelp.getByKey(dataId, sheetTypeEnum.getXbbRefTypeEnum().getCode(), saasMark, corpid);
                } else {
                    paasFormDataEntityExt = proGetHelp.getByKey(dataId, businessType, saasMark, corpid);
                }
                if ( saasDetailPermissionHelp.checkData(paasFormDataEntityExt, formDataDetailDTO.getSubBusinessType()) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                // 预防穿透没有标记，无法区分
                formId = paasFormDataEntityExt.getFormId();
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(paasFormDataEntityExt.getFormId(), corpid);
                if (Objects.nonNull(paasFormEntityExt)) {
                    distributorMark = paasFormEntityExt.getDistributorMark();
                    formDataDetailDTO.setDistributorMark(distributorMark);
                    // 把distributorMark再放进去
                    TransmittableThreadLocalUtil.setValue(saasMark, businessType, menuId, distributorMark);
                    if (Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                        boolean enable = paasAppService.validateAppEnable(null, XbbRefTypeEnum.DISTRIBUTOR.getAlias(), SaasMarkEnum.SAAS.getCode(), corpid);
                        if (!enable) {
                            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.DISTRIBUTOR_DISABLE);
                        }
                    }
                }
                if (Objects.nonNull(paasFormEntityExt) && Objects.equals(paasFormEntityExt.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())) {
                    paasFormDataEntityExt.setAppId(paasFormEntityExt.getAppId());
                    paasFormDataEntityExt.setMenuId(paasFormEntityExt.getMenuId());
                    businessType = XbbRefTypeEnum.transferBusinessType4Distributor(formDataDetailDTO.getBusinessType(), DistributorMarkEnum.DISTRIBUTOR.getCode());
                    subBusinessType = businessType;
                    formDataDetailDTO.setBusinessType(businessType);
                    formDataDetailDTO.setSubBusinessType(businessType);
                }
                handlerExplainDTO = initHandlerExplainDto(formDataDetailDTO, paasFormDataEntityExt);
                VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(loginUser, paasFormDataEntityExt);
                boolean hasDataPermission = commonPermissionHelp.checkViewPermission(verifyViewPermissionDTO);
                if (!Objects.equals(subBusinessType, XbbRefTypeEnum.CUSTOMER_RECYCLE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.CLUE_RECYCLE.getCode()) && !Objects.equals(subBusinessType, XbbRefTypeEnum.WORK_ORDER_ROB.getCode())
                        && !Objects.equals(subBusinessType, XbbRefTypeEnum.ONLINE_PAYMENT_FLOW.getCode()) && !hasDataPermission) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                }
                if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
                    // 工单特殊权限判断，工单模板授权人员
                    WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, corpid);
                    if ( Objects.isNull(workOrderFormEntityExt) ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                    }
                    WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(workOrderFormEntityExt.getTemplateId(), corpid);
                    // 工单详情页模板权限校验，工单模板设置的可见范围
                    if (!(loginUser.isAdminOrBoss() || loginUser.isMaxDataPermission())) {
                        String scopeRule = workOrderTemplateEntity.getScopeRule();
                        JSONObject scopeRuleObj =  JSONObject.parseObject(scopeRule);
                        String deptStr = scopeRuleObj.getString("dept");
                        List<Long> deptList = JSONArray.parseArray(deptStr, Long.class);
                        String userStr = scopeRuleObj.getString("user");
                        List<String> userList = JSONArray.parseArray(userStr, String.class);
                        if (deptList != null && userList != null) {
                            List<String> depUserIdList = new ArrayList<>();
                            if (deptList.size() > 0) {
                                // 获取子部门的depId
                                deptList = departmentModel.getSubDepIdList(corpid, deptList);
                                depUserIdList = userModel.getDepUserIdList(corpid, deptList);
                            }
                            userList.addAll(depUserIdList);
                            if (userList.size() > 0 && !userList.contains(userId)) {
                                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                            }
                        }
                    }
                }
                if (RedundantTemplateTypeEnum.isMultiTemplate(businessType)) {
                    PaasFormEntityExt paasFormEntity = paasFormModel.getByKey(formId, corpid);
                    if ( Objects.equals(paasFormEntity.getEnable(), 0) || Objects.equals(paasFormEntity.getDel(), 1) ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                    }
                    List<PaasFormEntityExt> formList = new ArrayList<>();
                    formList.add(paasFormEntity);
                    paasFormService.removeByPermission(formList, loginUser);
                    if ( formList.isEmpty() ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                    }
                }
                handelDetailPojo = new HandelDetailPojo(distributorMark, businessType, paasFormDataEntityExt, buttonPojoList, loginUser);
                // saas详情头部按钮
                proDetailHandlerHelp.handelDetailButton(handelDetailPojo);
                // saas头部关注按钮
                proDetailHandlerHelp.handelDetailFocus(businessType, titlePojo, paasFormDataEntityExt, userId);
                // saas头部印章
                proDetailHandlerHelp.handelDetailSeal(businessType, titlePojo, paasFormDataEntityExt);

                try {
                    // 只在客户模板中展示
                    if (fineClueHelp.hasBusinessSearch(businessType)) {
                        //搜客/工商查询老用户
                        String pid = fineClueHelp.getPidByCompanyName(corpid, paasFormDataEntityExt.getData().getString(CustomerManagementEnum.NAME.getAttr()) ,formDataDetailDTO.getPlatform());
                        if (Objects.nonNull(pid)) {
                            titlePojo.setPid(pid);
                        } else if (Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType)) {
                            // saas头部栗子详情页(开启搜客或者工商后提供)
                            proDetailHandlerHelp.handelDetailClue(titlePojo, paasFormDataEntityExt);
                        }
                    }
                } catch (Exception e) {
                    LOG.info("工商查询没有查询到该公司");
                }
                // saas 详情页头部标签
                //handelDetailTags(businessType, tags, paasFormDataEntityExt);/allList
                // saas关联新建工作流
                handelDetailPojo.setWorkFlowPojoList(workFlowPojoList);
                proDetailHandlerHelp.handelDetailWorkFlow(handelDetailPojo);
                // saas详情页特殊传参
                proDetailHandlerHelp.handleDetailSpecialParam(dataDetailPojo, paasFormDataEntityExt, businessType, loginUser);
                //详情页评分展示处理
                proDetailHandlerHelp.handelDetailScore(businessType,paasFormDataEntityExt,dataDetailPojo);
            } else {
                paasFormDataEntityExt = paasFormDataModel.getByKey(formDataDetailDTO.getDataId(), corpid);
                if ( Objects.isNull(paasFormDataEntityExt) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                appId = paasFormDataEntityExt.getAppId();
                formId = paasFormDataEntityExt.getFormId();
                handlerExplainDTO = initHandlerExplainDto(formDataDetailDTO, paasFormDataEntityExt);
                // 数据权限判断
                VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO(loginUser, paasFormDataEntityExt);
                boolean hasDataPermission = commonPermissionHelp.checkViewPermission(verifyViewPermissionDTO);
                if (!hasDataPermission) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                }
            }
            // 判断菜单和应用是否启用
            // 判断菜单和应用是否启用
            if (sheetFlag || Objects.equals(businessType, XbbRefTypeEnum.PAY_PLAN.getCode())) {
                validateAppAndMenuParentMenu(paasFormDataEntityExt.getAppId(), paasFormDataEntityExt.getMenuId(), corpid);
            } else {
                validateAppAndMenu(paasFormDataEntityExt.getAppId(), paasFormDataEntityExt.getMenuId(), corpid);
            }
            // 查看权限校验
            VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO();
            BeanUtil.copyProperties(formDataDetailDTO, verifyViewPermissionDTO);
            verifyViewPermissionDTO.setMenuId(paasFormDataEntityExt.getMenuId());
            ProPermissionHelp.verifyQueryPermission(verifyViewPermissionDTO);
            //审批中数据不让看，直接报错，目前这样处理，后续优化为可见，但没有任何操作权限
            if ( FlowStatusEnum.inApproval(paasFormDataEntityExt.getFlowStatus()) ) {
                throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200023);
            }

            List<LinkListPojo> linkList;
            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            List<FieldAttrEntity> explainList = handlerExplainDTO.getExplainList();
            JSONObject ownerAndCoUser = handlerExplainDTO.getOwnerAndCoUser();
            // ---- 获取用户和部门容器start
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(formDataDetailDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(explainList);
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();
            HandlerExplainVO handlerExplainVO;
            if (Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode())) {
                WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, corpid);
                if ( Objects.isNull(workOrderFormEntityExt) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
                }
                BeanUtil.copyProperties(workOrderFormEntityExt, paasFormEntityExt);
                //数据标签
                if ( workOrderFormEntityExt.getLabelsList().size() > 0 ) {
                    paasFormEntityExt.setLabelsList(Objects.toString(workOrderFormEntityExt.getLabelsList(), ""));
                    //顺便把标签字段也查询出
                    for(FieldAttrEntity fieldAttrEntity : explainList){
                        if(Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())){
                            labelField = fieldAttrEntity;
                            break;
                        }
                    }
                }
                //数据摘要
                if ( workOrderFormEntityExt.getSummaryList().size() > 0 ) {
                    paasFormEntityExt.setSummaryList(Objects.toString(workOrderFormEntityExt.getSummaryList(), ""));
                }
                linkList = JSONArray.parseArray(paasFormEntityExt.getAssociationList(), LinkListPojo.class);
                //工单form表没有这个两个字段,需要补充
                paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
                paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());

                Map<String, Object> param = BeanUtil.convertBean2Map(formDataDetailDTO, true);

                handlerExplainVO = workOrderFormDataFormExplainHandleName.handlerExplain(explainList, workOrderFormEntityExt, param, handlerExplainDTO);
            } else {
                PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
                if ( Objects.isNull(paasFormExplainEntity) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
                }
                paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
                if ( paasFormEntityExt == null ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
                }
                linkList = JSONArray.parseArray(paasFormEntityExt.getAssociationList(), LinkListPojo.class);
                explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
                if (Objects.equals(businessType, XbbRefTypeEnum.PRODUCT.getCode())) {
                    ProductFieldPojo productFieldPojo = saasFormHelp.getProductFieldPojo(RedisPrefixConstant.PRODUCT_UNIT, ProductEnum.UNIT.getAttr(), corpid);
                    for (FieldAttrEntity fieldAttrEntity : explainList) {
                        if (Objects.equals(fieldAttrEntity.getSaasAttr(), ProductEnum.UNIT.getSaasAttr())) {
                            fieldAttrEntity.setMultiItems(productFieldPojo.getMultiItems());
                            break;
                        }
                    }
                    paasFormExplainEntity.setExplains(JSON.toJSONString(explainList));
                }
                handlerExplainDTO.setPaasFormEntityExt(paasFormEntityExt);
                handlerExplainDTO.setFormData(paasFormDataEntityExt.getData());
                handlerExplainVO = formDataDetailFormExplainHandleName.handleExplain(handlerExplainDTO);
            }
            if ( handlerExplainVO == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            // 将处理后的值赋给 explainList
            explainList = handlerExplainVO.getHeadList();
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
            if ( CollectionsUtil.isNotEmpty(explainList) ) {
                for ( FieldAttrEntity fieldAttrEntity : explainList ) {
                    //顺便把标签字段查询出来
                    if(Objects.equals(FieldTypeEnum.LABEL.getType(),fieldAttrEntity.getFieldType())){
                        labelField = fieldAttrEntity;
                    }
                    explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
                }
            }
            //详情tab
            List<DetailTabPojo> tabPojoList = new ArrayList<>();
            if ( SaasMarkEnum.SAAS.getCode().equals(saasMark) ) {
                JSONObject data = paasFormDataEntityExt.getData();

                String creatorId = paasFormDataEntityExt.getCreatorId();


                // 设置系统字段
                // 设置创建者
                data.put(FieldTypeEnum.ADDTIME.getAlias(), paasFormDataEntityExt.getAddTime());
                data.put(FieldTypeEnum.UPDATETIME.getAlias(), paasFormDataEntityExt.getUpdateTime());
                data.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEntityExt.getSerialNo());
                data.put(FieldTypeEnum.CREATORID.getAlias(), creatorId);
                data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEntityExt.getDepartmentId());
                data.putAll(ownerAndCoUser);
                //  获取用户和部门容器 解析paas的特殊数据 end
                ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
                BeanUtil.copyProperties(formDataDetailDTO, parseSingleRowDataDTO);
                parseSingleRowDataDTO.setDataJsonObject(data);
                parseSingleRowDataDTO.setExplainMap(explainMap);
                parseSingleRowDataDTO.setUserMap(userMap);
                parseSingleRowDataDTO.setDepartmentMap(departmentMap);
                parseSingleRowDataDTO.setFormId(formId);
                // 解析数据
                ParseSingleRowDataVO parseSingleRowDataVO = formDataGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
                if ( Objects.isNull(parseSingleRowDataVO) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
                }
                data = parseSingleRowDataVO.getResult();
                Set<Object> linkDataSet = new HashSet<>();
                LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
                if ( !linkResultDataVO.getLinkDataSet().isEmpty() ) {
                    linkResultDataVO.getLinkDataSet().forEach((item -> {
                        linkDataSet.add(item);
                    }));
                }
                linkResultDataVO = linkResultDataVO == null ? new LinkResultDataVO() : linkResultDataVO;
                linkResultDataVO.setUserMap(userMap);
                linkResultDataVO.setDepartmentMap(departmentMap);
                FormDataGetDTO formDataGetDTO = new FormDataGetDTO();
                BeanUtil.copyProperties(formDataDetailDTO, formDataGetDTO);
                if ( !linkResultDataVO.getLinkData().isEmpty() && !linkResultDataVO.getLinkDataSet().isEmpty() ) {
                    linkResultDataVO.setData(data);
                    linkResultDataVO.setExplainMap(explainMap);
                    linkResultDataVO.setExplainList(explainList);
//                    data = formDataLinkDataGetServiceImpl.formDataLinkDataGet(formDataGetDTO, linkResultDataVO);
                }

                // saas详情头部摘要
                //handelDetailSecondTitle(businessType, secondTitle, paasFormDataEntityExt, explainMap);
                SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
                BeanUtil.copyProperties(formDataGetDTO, saasAnalysisDataDTO);
                //协同团队
                Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                userTeamService.getUserIdMap(Collections.singletonList(paasFormDataEntityExt.getDataId()),corpid,businessType,false,mainUserMap,coUserMap);

                // 当前数据的创建人、负责人、协同人、当前操作人
                handlerExplainDTO = new HandlerExplainDTO();
                handlerExplainDTO.setLoginUser(loginUser);
                handlerExplainDTO.setUserId(userId);
                handlerExplainDTO.setOwnerId(mainUserMap.get(paasFormDataEntityExt.getDataId()));
                handlerExplainDTO.setCoUserId(coUserMap.get(paasFormDataEntityExt.getDataId()));

                // 详情特殊返回字段
                proDetailHandlerHelp.handleDetailSpecialField(data, paasFormDataEntityExt.getId(), businessType, corpid, explainMap, formId, handlerExplainDTO);
                // saas特殊格式转换
                saasGetHelp.formatData(saasAnalysisDataDTO, data);
                //处理千分位
                FormDataGetVO formDataGetVO = new FormDataGetVO();
                formDataGetVO.setData(data);
                formDataGetAnalysisDataHelp.analysisGetOfThousandBits(formDataGetVO, explainList, false);
                //处理web端数据标签，摘要，标题
                proDetailHandlerHelp.handelDetail(saasMark,formId,data, businessType, explainMap, paasFormDataEntityExt, corpid, dataId, secondTitle, tags, paasFormEntityExt, explainList, titlePojo, subBusinessType, formDataDetailDTO.getUserId());

                //奇葩的逻辑：一个getDetail方法内，有两处判断-SaasMarkEnum.SAAS.getCode().equals(saasMark)，已经在上一个判断内初始化过handelDetailPojo
                handelDetailPojo.setTabPojoList(tabPojoList);
                // saas详情tab
                Integer feeType = packageHelp.getFeeType(corpid);
                proDetailHandlerHelp.handelDetailTab(handelDetailPojo, PlatFormEnum.WEB, explainMap, feeType);

            } else if ( SaasMarkEnum.PAAS.getCode().equals(saasMark) ) {
                //有团队的业务这边需要有权限的判断
                proDetailHandlerHelp.removeEditButtom(formDataDetailDTO, buttonPojoList, explainMap, paasFormDataEntityExt);
                //处理标签
                formDataDetailVO.setLabelEditAttr(labelHelp.dealWebDetailLabelListLocation(formDataDetailDTO, paasFormEntityExt.getLabelsList(),tags, paasFormDataEntityExt, labelField));
                // 为web拼装标题和摘要
                paasFormHelp.getWebTitleAndSummary(formDataDetailDTO, handlerExplainVO, titlePojo, secondTitle, paasFormDataEntityExt, paasFormEntityExt);
                proDetailHandlerHelp.handelCommonTags(paasFormDataEntityExt.getData(), businessType, explainMap, paasFormDataEntityExt, corpid, tags, paasFormEntityExt, subBusinessType, dataId, formDataDetailDTO.getUserId());
                UserFormPermissionVO userFormPermissionVO = userService.getUserFormPermissionInternal(corpid,
                        formDataDetailDTO.getUserId(), paasFormEntityExt.getAppId(), paasFormEntityExt.getMenuId());
                buttonPojoList = setDetailButtonPermission(userFormPermissionVO, formDataDetailDTO.getPlatform(), paasFormDataEntityExt.getDel());
                proDetailHandlerHelp.addPaasEsignBtn(userFormPermissionVO, formDataDetailDTO,paasFormDataEntityExt, buttonPojoList);
                //paas详情tab
                for ( PaasDetailTabEnum paasDetailTabEnum : PaasDetailTabEnum.values() ) {
                    if (Objects.equals(paasDetailTabEnum.getAnEnum().getKey(),PaasDetailTabEnum.STAGE_HISTORY.getAnEnum().getKey())){
                        continue;
                    }
                    if(Objects.equals(paasDetailTabEnum.getPlatform(), PlatFormEnum.DINGTALK)){
                        continue;
                    }
                    DetailTabPojo detailTabPojo = new DetailTabPojo();
                    BeanUtil.copyProperties(paasDetailTabEnum.getAnEnum(), detailTabPojo);
                    detailTabPojo.setAttr(paasDetailTabEnum.getAnEnum().getKey());
                    tabPojoList.add(detailTabPojo);
                }
                //判断当前客户阶段推进器字段可见权限，以及是否启用
                PaasFormExplainEntity explainEntity = paasFormExplainModel.getByFormId(formId, corpid);
                List<FieldAttrEntity> fieldAttrEntityList = JSONArray.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
                FieldAttrEntity stageFieldAttrEntity = null;
                for (FieldAttrEntity temp : fieldAttrEntityList) {
                    if (Objects.equals(temp.getFieldType(), FieldTypeEnum.STAGE_THRUSTER.getType())) {
                        stageFieldAttrEntity = temp;
                        break;
                    }
                }
                if (Objects.nonNull(stageFieldAttrEntity) && Objects.equals(stageFieldAttrEntity.getIsOpen(), 1)) {
                    Boolean attrCanSee = commonHelp.attrCanSee(stageFieldAttrEntity, dataId, paasFormEntityExt.getCreatorId(), formDataDetailDTO.getLoginUser(), corpid, 0);
                    if (attrCanSee) {
                        DetailTabPojo detailTabPojo = new DetailTabPojo();
                        BeanUtil.copyProperties(DetailTabEnum.STAGE_HISTORY, detailTabPojo);
                        detailTabPojo.setAttr(DetailTabEnum.STAGE_HISTORY.getKey());
                        tabPojoList.add(detailTabPojo);
                    }
                }
                proDetailHandlerHelp.handleTeamTab(tabPojoList, explainMap);
            }


            List<DetailTabPojo> detailTabList;
            handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(formDataDetailDTO, handlerExplainDTO);
            handlerExplainDTO.setOwnerId(ownerAndCoUser.getJSONArray(FieldTypeEnum.OWNERID.getAlias()).toJavaList(String.class));
            handlerExplainDTO.setCoUserId(ownerAndCoUser.getJSONArray(FieldTypeEnum.COUSERID.getAlias()).toJavaList(String.class));
            handlerExplainDTO.setCreatorId(paasFormDataEntityExt.getCreatorId());
            handlerExplainVO.setHandlerExplainDTO(handlerExplainDTO);
            if ( !Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), businessType) ) {
                detailTabList = ExplainUtil.getFieldListIncludeSubForm(handlerExplainVO, handlerExplainDTO);
                if (Objects.equals(businessType, XbbRefTypeEnum.COMMUNICATE_PLAN.getCode())) {
                    for (DetailTabPojo detailTabPojo : detailTabList) {
                        if (Objects.equals(detailTabPojo.getAttr(), CommunicatePlanEnum.CONTACT_WAY.getAttr())) {
                            // 这里需要将访客计划的联系方式字段的editHide置为0，bug：20848
                            detailTabPojo.getFieldAttrEntity().setEditHide(0);
                            break;
                        }
                    }
                }
                Integer business = businessType;
                detailTabList.removeIf(item -> Objects.equals(business, XbbRefTypeEnum.PRODUCT.getCode()) && Objects.equals(item.getAttr(),ProductEnum.STOCK_NOTIFY.getAttr()));
            } else {
                // 获取子表单tab栏
                detailTabList = ExplainUtil.getSubFormToTabWorkReport(handlerExplainVO, handlerExplainDTO);
            }

            if ( Objects.equals(DelEnum.NORMAL.getDel(), paasFormDataEntityExt.getDel()) ) {
                // 拼装关联列表的tab和按钮
                paasFormHelp.getLinkList(linkList, corpid);
                paasFormHelp.getLinkListTab(linkList, detailTabList, loginUser);
                paasFormHelp.getLinkListAddButton(linkList, workFlowPojoList, loginUser, PlatFormEnum.WEB);
                // 低代码按钮
                CustomButtonListDTO customButtonListDTO = new CustomButtonListDTO();
                customButtonListDTO.setBusinessType(formDataDetailDTO.getBusinessType());
                customButtonListDTO.setFormId(formId);
                customButtonListDTO.setSaasMark(formDataDetailDTO.getSaasMark());
                customButtonListDTO.setCorpid(formDataDetailDTO.getCorpid());
                customButtonListDTO.setLoginUser(formDataDetailDTO.getLoginUser());
                customButtonListDTO.setType(ButtonTypeEnum.DETAIL.getCode());
                CustomButtonListVO formCustomButtonListVO = customButtonService.listByPermission(customButtonListDTO);
                if (Objects.nonNull(formCustomButtonListVO) && CollectionsUtil.isNotEmpty(formCustomButtonListVO.getCustomButtonList())) {
                    formCustomButtonListVO.getCustomButtonList().forEach(item->{
                        WorkFlowPojo buttonPojo = new WorkFlowPojo();
                        buttonPojo.setActionList(item.getActionList());
                        buttonPojo.setValue(item.getName());
                        buttonPojo.setAttr(PaasConstant.LOW_CODE);
                        workFlowPojoList.add(buttonPojo);
                    });
                }
            }

            tabPojoList.addAll(detailTabList);
            proDetailHandlerHelp.addEsignTab4Saas(formDataDetailDTO,paasFormDataEntityExt, tabPojoList);
            cloudCodeHelp.setCloudCodeTab4Web(corpid, formDataDetailDTO.getLoginUser().getDynamicPermSet(), appId, formId, businessType, tabPojoList);
            cloudCodeHelp.setCloudCodeDetailButton4Web(corpid, formDataDetailDTO.getLoginUser().getDynamicPermSet(), appId, formId, businessType, buttonPojoList);
            // tab自定义排序
            tabPojoList = proDetailHandlerHelp.handleDetailTabSort(userId, corpid, formId, businessType, tabPojoList);

            //未开启工作流的公司不能查看审批记录
            boolean isOpenWorkflow = commonHelp.isOpenWorkFlow(corpid);
            if(!isOpenWorkflow){
                tabPojoList.removeIf(v -> Objects.equals(v.getAttr(), DetailTabEnum.APPROVAL_RECORDS.getKey()));
            }

            // 呼叫中心权限
            boolean isActiveCall = openCall(userId, corpid, businessType);
            List<DetaPhonePojo> dial = new ArrayList<>();
            if ( isActiveCall ) {
                dial = saasListHelp.cusCallPhone(paasFormDataEntityExt.getData(), businessType, corpid, explainMap, handlerExplainDTO);
            }
            //阿里云呼叫中心权限
            boolean isActiveAliyunCall = openAliyunCall(userId, corpid, businessType);
            List<DetaPhonePojo> aliyunCallCenterDial = new ArrayList<>();
            if ( isActiveAliyunCall ) {
                aliyunCallCenterDial = saasListHelp.cusCallPhone(paasFormDataEntityExt.getData(), businessType, corpid, explainMap, handlerExplainDTO);
                if(CollectionUtils.isNotEmpty(aliyunCallCenterDial)&&StringUtil.isNotEmpty(aliyunCallCenterDial.get(0).getPhoneNum())){
                    dataDetailPojo.setAliyunCallCenterDial(aliyunCallCenterDial);
                }
            }
            //校验套餐类型
            Integer feeType = packageHelp.getFeeType(corpid);
            if (!Objects.equals(feeType,PackageTypeEnum.STANDARD.getType())){
                boolean hasOuterLinkShare = outerLinkModel.checkOuterLinkEnable(formId, OuterLinkTypeEnum.SHARE.getCode(), corpid);
                if (hasOuterLinkShare) {
                    dataDetailPojo.setHasOuterLinkShare(BasicConstant.ONE);
                }
            }
            dataDetailPojo.setTabSortPermission(loginUser.isAdminOrBoss());
            dataDetailPojo.setButton(buttonPojoList);
            dataDetailPojo.setDial(dial);
            dataDetailPojo.setTitle(titlePojo);
            dataDetailPojo.setSecondTitle(secondTitle);
            dataDetailPojo.setTags(tags);
            dataDetailPojo.setWorkFlow(workFlowPojoList);
            formDataDetailVO.setTab(tabPojoList);
            formDataDetailVO.setHead(dataDetailPojo);
            formDataDetailVO.setPaasFormEntityExt(paasFormEntityExt);
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("formDataService.detail报错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return formDataDetailVO;
    }

    /**
     * 初始化HandlerExplainDTO,做一些基本操作
     *
     * @param formDataDetailDTO
     * @param paasFormDataEntityExt
     * @return
     * @throws XbbException
     */
    private HandlerExplainDTO initHandlerExplainDto(FormDataDetailDTO formDataDetailDTO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException{
        Long formId = paasFormDataEntityExt.getFormId();
        String corpid = formDataDetailDTO.getCorpid();
        PaasFormExplainEntity paasFormExplainEntity = proFormHelp.getExplainEntity(corpid, formId, formDataDetailDTO.getBusinessType());
        paasFormDataEntityExt.setMenuId(paasFormExplainEntity.getMenuId());
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
        BeanUtil.copyProperties(formDataDetailDTO, handlerExplainDTO, false);
        Map<String, UserEntity> userMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        handlerExplainDTO.setExplainList(explainList);
        // 获取协同人和负责人
        JSONObject ownerAndCoUser = paasFormHelp.getOwnerIdAndCoUserId(handlerExplainDTO, formDataDetailDTO.getSaasMark(),
                formDataDetailDTO.getBusinessType(), formDataDetailDTO.getSubBusinessType(), paasFormDataEntityExt, userMap);
        paasFormDataEntityExt.getData().putAll(ownerAndCoUser);
        handlerExplainDTO.setUserMap(userMap);
        handlerExplainDTO.setOwnerAndCoUser(ownerAndCoUser);
        return handlerExplainDTO;
    }


    /**
     * Description: 获取saas详情框架（mobile端工单独用）
     *
     * @param mobileFormDataDetailDTO
     * @return FormDataDetailVO
     * @throws XbbException
     * @author 刘阳
     * @date 2019/5/6 3:16 PM
     * @since v1.0
     */
    @Override
    public MobileFormDataDetailVO getWorkOrderMoblieDetail(MobileFormDataDetailDTO mobileFormDataDetailDTO) throws XbbException {
        MobileFormDataDetailVO mobileFormDataDetailVO = new MobileFormDataDetailVO();
        List<WorkFlowPojo> workFlowPojoList = new ArrayList<>();
        List<FieldAttrEntity> explainList = new ArrayList<>();
        List<FieldAttrEntity> headList = new ArrayList<>();
        List<SummaryDataPoJo> summaryList = new ArrayList<>();
        List<SummaryDataPoJo> summaryList1 = new ArrayList<>();
        List<FormTitlePoJo> formTitleList = new ArrayList<>();
        // 查看权限校验
        VerifyViewPermissionDTO verifyViewPermissionDTO = new VerifyViewPermissionDTO();
        BeanUtil.copyProperties(mobileFormDataDetailDTO, verifyViewPermissionDTO);
        ProPermissionHelp.verifyQueryPermission(verifyViewPermissionDTO);
        try {
            String userId = mobileFormDataDetailDTO.getUserId();
            String corpid = mobileFormDataDetailDTO.getCorpid();
            Long dataId = mobileFormDataDetailDTO.getDataId();
            Integer businessType = mobileFormDataDetailDTO.getBusinessType();
            Integer saasMark = mobileFormDataDetailDTO.getSaasMark();
            Integer subBusinessType = mobileFormDataDetailDTO.getSubBusinessType();
            PaasFormDataEntityExt paasFormDataEntityExt;
            WorkOrderEntity workOrderEntity = new WorkOrderEntity();
            JSONObject data = new JSONObject();
            UserVO loginUser = mobileFormDataDetailDTO.getLoginUser();
            Long formId;
            paasFormDataEntityExt = proGetHelp.getByKey(dataId, mobileFormDataDetailDTO.getBusinessType(), saasMark, corpid);
            if ( Objects.isNull(paasFormDataEntityExt) || Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            // 数据权限判断
            boolean hasDataPermission = commonPermissionHelp.checkViewPermission(verifyViewPermissionDTO);
            if (!Objects.equals(subBusinessType, XbbRefTypeEnum.WORK_ORDER_ROB.getCode()) && !hasDataPermission) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
            }
            formId = paasFormDataEntityExt.getFormId();
            WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formId, corpid);
            if ( Objects.isNull(workOrderFormEntityExt) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            WorkOrderTemplateEntity workOrderTemplateEntity = workOrderTemplateModel.getBykey(workOrderFormEntityExt.getTemplateId(), corpid);
            // 工单详情页模板权限校验，工单模板设置的可见范围
            if (!(loginUser.isAdminOrBoss() || loginUser.isMaxDataPermission())) {
                String scopeRule = workOrderTemplateEntity.getScopeRule();
                JSONObject scopeRuleObj =  JSONObject.parseObject(scopeRule);
                String deptStr = scopeRuleObj.getString("dept");
                List<Long> deptList = JSONArray.parseArray(deptStr, Long.class);
                String userStr = scopeRuleObj.getString("user");
                List<String> userList = JSONArray.parseArray(userStr, String.class);
                if (deptList != null && userList != null) {
                    List<String> depUserIdList = new ArrayList<>();
                    if (deptList.size() > 0) {
                        // 获取子部门的depId
                        deptList = departmentModel.getSubDepIdList(corpid, deptList);
                        depUserIdList = userModel.getDepUserIdList(corpid, deptList);
                    }
                    userList.addAll(depUserIdList);
                    if (userList.size() > 0 && !userList.contains(userId)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
                    }
                }
            }


            // 判断菜单和应用是否启用
            validateAppAndMenu(paasFormDataEntityExt.getAppId(), paasFormDataEntityExt.getMenuId(), corpid);
            // saas关联新建工作流
            proDetailHandlerHelp.handelDetailWorkFlow(businessType, paasFormDataEntityExt, workFlowPojoList, loginUser);

            //审批中数据不让看，直接报错，目前这样处理，后续优化为可见，但没有任何操作权限
            if ( FlowStatusEnum.inApproval(paasFormDataEntityExt.getFlowStatus()) ) {
                throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200023);
            }

            data = paasFormDataEntityExt.getData();

            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            HandlerExplainVO handlerExplainVO;
            JSONArray summaryList2 = new JSONArray();
            workOrderEntity = workOrderModel.getByKey(dataId, corpid);
            WorkOrderExplainEntity workOrderExplainEntity = workOrderExplainModel.getByFormId(formId, corpid);
            if ( Objects.isNull(workOrderExplainEntity) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }

            BeanUtil.copyProperties(workOrderFormEntityExt, paasFormEntityExt);
            //数据摘要
            summaryList2 = workOrderFormEntityExt.getSummaryList();
            //数据标签
            paasFormEntityExt.setSummaryList(summaryList2.toString());
            paasFormEntityExt.setLabelsList(workOrderFormEntityExt.getLabelsList().toString());
            //工单form表没有这个两个字段,需要补充
            paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
            explainList = JSONArray.parseArray(workOrderExplainEntity.getExplains(), FieldAttrEntity.class);
            //顺便把标签字段也查询出来
            FieldAttrEntity labelField = null;
            for(FieldAttrEntity fieldAttrEntity : explainList){
                if(Objects.equals(fieldAttrEntity.getFieldType(), FieldTypeEnum.LABEL.getType())){
                    labelField = fieldAttrEntity;
                    break;
                }
            }
            // ---- 获取用户和部门容器start
            UserAndDepartmentGetDTO userAndDepartmentGetDTO = new UserAndDepartmentGetDTO();
            BeanUtil.copyProperties(mobileFormDataDetailDTO, userAndDepartmentGetDTO);
            userAndDepartmentGetDTO.setExplainList(explainList);
            UserAndDepartmentGetVO userAndDepartmentGetVO = userHelp.getUserDepartmentMap(userAndDepartmentGetDTO);
            Map<String, UserEntity> userMap = userAndDepartmentGetVO.getUserMap();
            Map<String, DepartmentEntity> departmentMap = userAndDepartmentGetVO.getDepartmentMap();

            //  获取字段解释信息，并且过滤不可见字段 start
            HandlerExplainDTO handlerExplainDTO = new HandlerExplainDTO();
            BeanUtil.copyProperties(mobileFormDataDetailDTO, handlerExplainDTO, false);
            Map<String, Object> param = BeanUtil.convertBean2Map(mobileFormDataDetailDTO, true);
            handlerExplainDTO.setExplainList(explainList);
            paasFormHelp.getOwnerIdAndCoUserId(handlerExplainDTO, SaasMarkEnum.SAAS.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode(), XbbRefTypeEnum.WORK_ORDER.getCode(), paasFormDataEntityExt, userMap);
            handlerExplainVO = workOrderFormDataFormExplainHandleName.handlerExplain(explainList, workOrderFormEntityExt, param, handlerExplainDTO);
            if ( handlerExplainVO == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
            }
            // 把解析完的字段拿出来
            explainList = handlerExplainVO.getHeadList();
            headList = paasFormExplainService.handleExplainList(explainList, businessType, corpid, formId);
            // 获取字段解释信息，并且过滤不可见字段 end
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(headList.size());
            // 将字段放入字段容器
            for ( FieldAttrEntity fieldAttrEntity : headList ) {
                explainMap.put(fieldAttrEntity.getAttr(), fieldAttrEntity);
            }

            String creatorId = paasFormDataEntityExt.getCreatorId();
            FormDataGetDTO formDataGetDTO = new FormDataGetDTO();
            BeanUtil.copyProperties(mobileFormDataDetailDTO, formDataGetDTO);
            // 设置系统字段 设置创建者
            data.put(FieldTypeEnum.ADDTIME.getAlias(), paasFormDataEntityExt.getAddTime());
            data.put(FieldTypeEnum.UPDATETIME.getAlias(), paasFormDataEntityExt.getUpdateTime());
            data.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEntityExt.getSerialNo());
            data.put(FieldTypeEnum.CREATORID.getAlias(), creatorId);
            data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEntityExt.getDepartmentId());
            // 设置协同人和负责人
            userHelp.setOwnerAndCoUser(data, paasFormDataEntityExt, saasMark, businessType, userMap);

            //  获取用户和部门容器 解析paas的特殊数据 end
            ParseSingleRowDataDTO parseSingleRowDataDTO = new ParseSingleRowDataDTO();
            BeanUtil.copyProperties(mobileFormDataDetailDTO, parseSingleRowDataDTO);
            parseSingleRowDataDTO.setDataJsonObject(data);
            parseSingleRowDataDTO.setExplainMap(explainMap);
            parseSingleRowDataDTO.setUserMap(userMap);
            parseSingleRowDataDTO.setDepartmentMap(departmentMap);
            // 解析数据
            ParseSingleRowDataVO parseSingleRowDataVO = formDataGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
            if ( Objects.isNull(parseSingleRowDataVO) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.PARSE_SINGLE_ROW_DATA_FAILED);
            }
            LinkResultDataVO linkResultDataVO = parseSingleRowDataVO.getLinkResultDataVO();
            linkResultDataVO = linkResultDataVO == null ? new LinkResultDataVO() : linkResultDataVO;
            linkResultDataVO.setUserMap(userMap);
            linkResultDataVO.setDepartmentMap(departmentMap);
            data = parseSingleRowDataVO.getResult();
//            if ( !linkResultDataVO.getLinkData().isEmpty() && !linkResultDataVO.getLinkDataSet().isEmpty() ) {
//                linkResultDataVO.setData(data);
//                linkResultDataVO.setExplainMap(explainMap);
//                linkResultDataVO.setExplainList(headList);
//                data = formDataLinkDataGetServiceImpl.formDataLinkDataGet(formDataGetDTO, linkResultDataVO);
//            }
            // 处理关联数据逻辑 end

            //处理千分位的问题
            FormDataGetVO formDataGetVO1 = new FormDataGetVO();
            formDataGetVO1.setData(data);
            formDataGetAnalysisDataHelp.analysisGetOfThousandBits(formDataGetVO1, explainList, false);

            // 处理标题和摘要，标签 start
            List<SummaryDataPoJo> labelsList = new ArrayList<>();
            if ( Objects.nonNull(paasFormEntityExt.getLabelsList()) ) {
                labelsList = ExplainUtil.getSpecialSummaryList(paasFormEntityExt.getLabelsList(), data, explainMap, paasFormDataEntityExt);
                if ( Objects.equals(saasMark, SaasMarkEnum.SAAS.getCode()) ) {
                    // SaaS业务特殊处理，将数据字典的key值转成显示的value值
                    mobileDetailService.transferKeyToShowValue(corpid, labelsList, businessType);
                }
            }
            handleWorkOrderAppDetailLabellist(labelsList);
            mobileFormDataDetailVO.setLabelsList(labelsList);

            // 解析标题
            formTitleList = ExplainUtil.getWorkOrderFormTitle(JSONArray.parseArray(paasFormEntityExt.getCustomTitle()), explainMap, data, explainList, workOrderEntity);

            List<LinkListPojo> linkList = JSONArray.parseArray(paasFormEntityExt.getAssociationList(), LinkListPojo.class);
            mobileFormDataDetailVO.setTitleList(formTitleList);
            List<DetailTabPojo> tabPojoList = new ArrayList<>();
            // 移动端SaaS详情页额外展示信息
            if ( !Objects.equals(workOrderTemplateEntity.getIsFree(), 1) ) {
                //指定流程才有阶段
                SummaryDataPoJo summary = new SummaryDataPoJo();
                if (!Objects.equals(workOrderEntity.getNowStageId(), 0L)) {
                    WorkOrderStageEntity workOrderStageEntity = workOrderStageModel.getByKey(workOrderEntity.getNowStageId(), workOrderEntity.getCorpid());
                    summary.setValue(Collections.singletonList(workOrderStageEntity.getName()));
                    summary.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.STAGE_NAME));
                    summaryList1.add(summary);
                }
            }
            //自由流程不限时工单
            boolean isLimit = Objects.equals(workOrderTemplateEntity.getIsFree(), 1) && Objects.equals(workOrderTemplateEntity.getExpectedTime(), 0);
            WorkOrderFlowNodeEntity workOrderFlowNodeEntity = workOrderFlowNodeModel.getNode(workOrderEntity.getId(), 1, corpid).get(0);
            SummaryDataPoJo summary1 = new SummaryDataPoJo();
            if ( isLimit ) {
                summary1.setValue(Collections.singletonList(""));
            } else {
                summary1.setValue(Collections.singletonList(workOrderBasicService.workOrderNodeConsueTime(workOrderFlowNodeEntity).getConsumeTimeStr()));
            }
            summary1.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.STAGE_TIME_CONSUMING));
            summaryList1.add(summary1);

            WorkOrderEntityExt workOrderEntityExt = new WorkOrderEntityExt();
            BeanUtil.copyProperties(workOrderEntity, workOrderEntityExt);
            SummaryDataPoJo summary2 = new SummaryDataPoJo();
            if ( isLimit ) {
                summary2.setValue(Collections.singletonList(workOrderBasicService.workOrderSpecialConsueTime(workOrderEntityExt).getConsumeTimeStr()));
            } else {
                summary2.setValue(Collections.singletonList(workOrderBasicService.workOrderConsueTime(workOrderEntityExt).getConsumeTimeStr()));
            }
            summary2.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.WORKORDER_TIME_CONSUMING));
            summaryList1.add(summary2);
            summaryList = ExplainUtil.getSpecialSummaryList(summaryList2, data, explainMap, paasFormDataEntityExt);
            summaryList.addAll(summaryList1);
            mobileDetailService.transferKeyToShowValue(corpid, summaryList, businessType);
            mobileDetailService.handleSummarySpecialAttr(corpid, summaryList, businessType, data, dataId, paasFormDataEntityExt);
            mobileFormDataDetailVO.setSummaryList(summaryList);

//            MobileDetailSpecialInfoPojo specialInfoPojo = mobileDetailService.getMobileDetailSpecialInfo(null, corpid, userId, businessType, dataId, data, explainMap, paasFormDataEntityExt.getFlowStatus());
            MobileDetailSpecialInfoPojo specialInfoPojo = mobileDetailService.getMobileDetailSpecialInfo(null,corpid, formDataGetDTO.getLoginUser(), businessType,paasFormDataEntityExt,explainMap);
            mobileFormDataDetailVO.setRightSpecialInfo(specialInfoPojo);

            JSONArray bottomBlockInfo = mobileDetailService.getBottomBlockInfo(corpid, userId, businessType, dataId, data, explainMap, paasFormDataEntityExt, formDataGetDTO);
            //工单工作流
            if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                List<ItemPoJo> itemPoJoList = new ArrayList<>();
                for ( WorkFlowPojo pojo : workFlowPojoList ) {
                    ItemPoJo itemPoJo = new ItemPoJo();
                    itemPoJo.setText(pojo.getValue());
                    itemPoJo.setValue(pojo.getAttr());
                    itemPoJoList.add(itemPoJo);
                }
                MobileDetailStatusBlockPojo statusBlockPojo = new MobileDetailStatusBlockPojo();
                statusBlockPojo.setOptions(itemPoJoList);
                bottomBlockInfo.add(statusBlockPojo);
                //工单状态
                WorkOrderStatusEnum workOrderStatusEnum = WorkOrderStatusEnum.getByCode(workOrderEntity.getStatus());
                mobileFormDataDetailVO.setWorkOrderStatus(workOrderStatusEnum.getName());
            }

            mobileFormDataDetailVO.setBottomBlockInfo(bottomBlockInfo);
            // 之前的逻辑是不做权限处理，现改成对它进行权限控制
            List<BusinessDetailTabEnum> tabEnumList = BusinessDetailTabEnum.getByBusinessTypeAndPermissionForDingtalk(businessType, loginUser.getPermSet());
            for ( BusinessDetailTabEnum tabEnum : tabEnumList ) {
                DetailTabPojo detailTabPojo = new DetailTabPojo();
                BeanUtil.copyProperties(tabEnum.getAnEnum(), detailTabPojo);
                detailTabPojo.setAttr(detailTabPojo.getKey());
                tabPojoList.add(detailTabPojo);
            }
            handlerExplainDTO.setOwnerId(data.getJSONArray(FieldTypeEnum.OWNERID.getAlias()).toJavaList(String.class));
            handlerExplainDTO.setCoUserId(data.getJSONArray(FieldTypeEnum.COUSERID.getAlias()).toJavaList(String.class));
            handlerExplainVO.setHandlerExplainDTO(handlerExplainDTO);
            List<DetailTabPojo> tabList = ExplainUtil.getFieldListIncludeSubForm(handlerExplainVO, handlerExplainDTO);
            tabPojoList.addAll(tabList);
            // 拼装关联列表的tab和按钮
            paasFormHelp.getLinkList(linkList, corpid);
            paasFormHelp.getLinkListTab(linkList, tabPojoList, loginUser);
            paasFormHelp.getLinkListAddButton(linkList, workFlowPojoList, loginUser, PlatFormEnum.DINGTALK);

            // tab自定义排序
            tabPojoList = proDetailHandlerHelp.handleDetailTabSort(userId, corpid, formId, businessType, tabPojoList);
            mobileFormDataDetailVO.setTab(tabPojoList);
            //上部按钮权限
            FormDataGetVO formDataGetVO = new FormDataGetVO();
            BeanUtil.copyProperties(mobileFormDataDetailVO, formDataGetVO);
            // 解析saas pro的特殊数据，包括下拉框的回显
            PaasFormDataEsListVO paasFormDataEsListVO = new PaasFormDataEsListVO();
            List<PaasFormDataEntityExt> formDataEsEntities = new ArrayList<>();
            PaasFormDataEntityExt paasFormDataEsEntity = new PaasFormDataEntityExt();
            BeanUtil.copyProperties(paasFormDataEntityExt, paasFormDataEsEntity);
            paasFormDataEsEntity.setData(data);
            formDataEsEntities.add(paasFormDataEsEntity);
            paasFormDataEsListVO.setPaasFormDataESList(formDataEsEntities);
            saasListHelp.analysisSaasDataList(paasFormDataEsListVO, explainMap);
            formDataEsEntities = paasFormDataEsListVO.getPaasFormDataESList();
            data = formDataEsEntities.get(0).getData();
            mobileFormDataDetailVO.setData(data);
            if ( Objects.equals(mobileFormDataDetailDTO.getSaasMark(), SaasMarkEnum.SAAS.getCode()) && Objects.equals(PlatFormEnum.DINGTALK.getValue(), mobileFormDataDetailDTO.getPlatform()) ) {
                // 设置移动端详情右上角操作
                mobileDetailService.handelMobileWorkFlow(loginUser, businessType, formDataGetVO, paasFormDataEntityExt);
                List<TopPermissionsPoJo> topPermission = formDataGetVO.getTopPermissions();
                if ( CollectionsUtil.isNotEmpty(linkList) ) {
                    // 设置关联列表的按钮
                    paasFormHelp.setMobileLinkListButton(topPermission, linkList, mobileFormDataDetailDTO.getLoginUser());
                }
                // 低代码按钮
                CustomButtonListDTO customButtonListDTO = new CustomButtonListDTO();
                customButtonListDTO.setBusinessType(mobileFormDataDetailDTO.getBusinessType());
                customButtonListDTO.setFormId(formId);
                customButtonListDTO.setSaasMark(mobileFormDataDetailDTO.getSaasMark());
                customButtonListDTO.setCorpid(mobileFormDataDetailDTO.getCorpid());
                customButtonListDTO.setLoginUser(mobileFormDataDetailDTO.getLoginUser());
                customButtonListDTO.setType(ButtonTypeEnum.DETAIL.getCode());
                CustomButtonListVO formCustomButtonListVO = customButtonService.listByPermission(customButtonListDTO);
                if (Objects.nonNull(formCustomButtonListVO) && CollectionsUtil.isNotEmpty(formCustomButtonListVO.getCustomButtonList())) {
                    for (CustomButtonPojo item : formCustomButtonListVO.getCustomButtonList()) {
                        TopPermissionsPoJo buttonPojo = new TopPermissionsPoJo();
                        buttonPojo.setActionList(item.getActionList());
                        buttonPojo.setValue(item.getName());
                        buttonPojo.setAttr(PaasConstant.LOW_CODE+StringConstant.UNDER_LINE+item.getId());
                        buttonPojo.setBtnType(PaasConstant.LOW_CODE);
                        topPermission.add(buttonPojo);
                    }
                }
                mobileFormDataDetailVO.setTopPermissions(topPermission);
                // SaaS移动端详情底部操作
                List<TopPermissionsPoJo> button = mobileDetailService.getMobileDetailBottomOperation(businessType, paasFormDataEntityExt, loginUser);
                //工单在没有工作流为空时，底部工单操作不回显
                if ( Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                    JSONObject jsonObject = mobileFormDataDetailVO.getBottomBlockInfo().getJSONObject(1);
                    JSONArray jsonArray = jsonObject.getJSONArray("options");
                    if ( jsonArray.size() == 0 || jsonArray == null ) {
                        TopPermissionsPoJo topPermissionsPoJo = new TopPermissionsPoJo();
                        BeanUtil.copyProperties(MobileDetailBottomOperationEnum.WORK_ORDER_OPERATION, topPermissionsPoJo);
                        Iterator<TopPermissionsPoJo> iterator = button.iterator();
                        while (iterator.hasNext()) {
                            TopPermissionsPoJo topPermissionsPoJo1 = iterator.next();
                            String value = topPermissionsPoJo.getValue();
                            String value1 = topPermissionsPoJo1.getValue();
                            if ( Objects.equals(value, value1) ) {
                                iterator.remove();
                            }
                        }
                    }
                }
                // 没有地址字段或者没有编辑权限的没有编辑按钮
                FieldAttrEntity fieldAttrEntity = explainMap.get(WorkOrderEnum.ADDRESS.getAttr());
                if (Objects.nonNull(fieldAttrEntity) && Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ONE)) {
                    Boolean editableOfScope = ExplainUtil.isEditableOfScope(fieldAttrEntity, handlerExplainDTO);
                    if (!editableOfScope) {
                        button = button.stream().filter(v -> !Objects.equals(v.getAttr(), MobileDetailBottomOperationEnum.WORK_ORDER_LOCATION.getAttr())).collect(Collectors.toList());
                    }
                } else {
                    button = button.stream().filter(v -> !Objects.equals(v.getAttr(), MobileDetailBottomOperationEnum.WORK_ORDER_LOCATION.getAttr())).collect(Collectors.toList());
                }


                FormDataDetailDTO formDataDetailDTO = new FormDataDetailDTO();
                BeanUtil.copyProperties(mobileFormDataDetailDTO, formDataDetailDTO);
                String labelEditAttr = labelHelp.dealAppDetailLabelListLocation(formDataDetailDTO, mobileFormDataDetailVO.getLabelsList(), paasFormDataEntityExt, labelField);
                mobileFormDataDetailVO.setBottomOperation(button);
                mobileFormDataDetailVO.setLabelEditAttr(labelEditAttr);
                mobileFormDataDetailVO.setPaasFormEntity(paasFormEntityExt);
                //校验套餐类型
                Integer feeType = packageHelp.getFeeType(corpid);
                if (!Objects.equals(feeType,PackageTypeEnum.STANDARD.getType())){
                    boolean hasOuterLinkShare = outerLinkModel.checkOuterLinkEnable(formId, OuterLinkTypeEnum.SHARE.getCode(), corpid);
                    if (hasOuterLinkShare) {
                        mobileFormDataDetailVO.setHasOuterLinkShare(BasicConstant.ONE);
                    }
                }
            }
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData数据库查询表单数据出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return mobileFormDataDetailVO;
    }

    /**
     * 恶性的处理一下，兜底
     */
    private void  handleWorkOrderAppDetailLabellist(List<SummaryDataPoJo> labelsList){
        try {
            if(CollectionsUtil.isNotEmpty(labelsList)){
                for(SummaryDataPoJo summaryDataPoJo : labelsList){
                    //标签的值
                    if(Objects.equals(summaryDataPoJo.getFieldType(),FieldTypeEnum.LABEL.getType())){
                        //value [[{},{}]]
                        List<Object> value = summaryDataPoJo.getValue();
                        if(CollectionsUtil.isNotEmpty(value)){
                            //[{},{}]
                            Object firstValue = value.get(0);
                            if(firstValue instanceof List){
                                summaryDataPoJo.setValue((List)firstValue);
                            }
                        }
                    }
                }
            }
        } catch (Exception exception) {
            LOG.error("handleWorkOrderAppDetailLabel 异常,e{}", exception.getMessage());
        }
    }


    @Override
    public DataInfoVO dataInfo(DataInfoDTO dataInfoDTO) throws XbbException {
        DataInfoVO dataInfoVO = new DataInfoVO();
        try {
            if ( SaasMarkEnum.SAAS.getCode().equals(dataInfoDTO.getSaasMark()) ) {
                Integer businessType = XbbRefTypeEnum.transferBusinessType4Distributor(dataInfoDTO.getSubBusinessType(), dataInfoDTO.getDistributorMark());
                if ( Objects.isNull(dataInfoDTO.getMenuId()) || Objects.equals(dataInfoDTO.getMenuId(), -1L) ) {
                    PageTitleEnum pageTitleEnum = PageTitleEnum.getByCode(businessType);
                    dataInfoVO.setPageTitle(pageTitleEnum == null ? null : pageTitleEnum.getName());
                } else {
                    PaasMenuEntity paasMenuEntity = paasMenuModel.getByKey(dataInfoDTO.getMenuId(), dataInfoDTO.getCorpid());
                    if ( Objects.isNull(paasMenuEntity) ) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
                    }
                    dataInfoVO.setPageTitle(paasMenuEntity.getName());
                }
                //如果是知识库获取某个知识库名称
                if(Objects.equals(businessType, XbbRefTypeEnum.KNOWLEDGE_BASE.getCode())){
                    KnowledgeBaseEntity knowledgeBaseEntity=knowledgeBaseModel.getByKey(dataInfoDTO.getDataId(),dataInfoDTO.getCorpid());
                    dataInfoVO.setPageTitle(knowledgeBaseEntity.getKnowledgeName());
                }
                if (Objects.equals(businessType , XbbRefTypeEnum.WAIT_INSTOCK_PURCHASE.getCode()) && Objects.equals(dataInfoDTO.getBusinessType() , XbbRefTypeEnum.PURCHASE.getCode())){
                    businessType = dataInfoDTO.getBusinessType();
                }
                if((Objects.equals(businessType , XbbRefTypeEnum.WAIT_OUTSTOCK.getCode()) || (Objects.equals(businessType , XbbRefTypeEnum.WAIT_PURCHASE.getCode()))) && Objects.equals(dataInfoDTO.getBusinessType() , XbbRefTypeEnum.CONTRACT.getCode())){
                    businessType = dataInfoDTO.getBusinessType();
                }
                PlaceholderEnum placeholderEnum = PlaceholderEnum.getByCode(businessType, dataInfoDTO.getDistributorMark());
                dataInfoVO.setSearchPlaceholder(placeholderEnum.getName());

                if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
                    PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(dataInfoDTO.getFormId(),dataInfoDTO.getCorpid());
                    if(Objects.nonNull(paasFormExplainEntity) && Objects.equals(paasFormExplainEntity.getDel(), DelEnum.NORMAL.getDel())) {
                        String explains = paasFormExplainEntity.getExplains();
                        if(Objects.nonNull(explains)) {
                            Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, null);
                            if(explainMap != null){
                                FieldAttrEntity fieldAttrEntity = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                                if(Objects.nonNull(fieldAttrEntity) && (Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ZERO) || Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ZERO))){
                                    // 电话字段不可见，去除电话字段模糊搜索，暂时借用PlaceholderEnum.CUSTOMER_COMMUNICATE.getName()
                                    dataInfoVO.setSearchPlaceholder(PlaceholderEnum.CUSTOMER_COMMUNICATE.getName());
                                }
                            }
                        }
                    }
                }

                RowNameEnum rowNameEnum = RowNameEnum.getByBusinessType(businessType);
                dataInfoVO.setRowName(rowNameEnum.getAttr());
            } else {
                String corpid = dataInfoDTO.getCorpid();
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByMenuId(dataInfoDTO.getMenuId(), corpid);
                if ( Objects.isNull(paasFormEntityExt) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
                }
                dataInfoVO.setPageTitle(paasFormEntityExt.getName());
                if ( StringUtil.isNotEmpty(paasFormEntityExt.getCustomTitle()) ) {
                    List<FormTitlePoJo> titleList = JSONArray.parseArray(paasFormEntityExt.getCustomTitle()).toJavaList(FormTitlePoJo.class);
                    if ( !titleList.isEmpty() ) {
                        for ( FormTitlePoJo item : titleList ) {
                            if ( StringUtil.isNotEmpty(item.getAttr()) ) {
                                dataInfoVO.setRowName(item.getAttr());
                                break;
                            }
                        }
                    }
                }
                dataInfoVO.setSearchPlaceholder(I18nMessageUtil.getMessage(I18nStringConstant.SIMPLATE_FIELD_SEARCH));
            }
        }  catch (XbbException e){
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormDataServiceImpl.dataInfo 出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return dataInfoVO;
    }

    /**
     * 客户列表查重渲染
     *
     * @param customerRepeatDTO
     * @return
     */
    @Override
    public CustomerRepeatVO customerRepeat(CustomerRepeatDTO customerRepeatDTO) throws XbbException {
        CustomerRepeatVO repeatVO = new CustomerRepeatVO();
        Integer businessType = customerRepeatDTO.getBusinessType();
        String corpid = customerRepeatDTO.getCorpid();
        List<RepeatPojo> repeatTitles = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if(Objects.equals(businessType, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())){
            RepeatPojo repeatPojo1 = new RepeatPojo(BasicConstant.ONE, I18nMessageUtil.getMessage(BusinessConstant.REPEAT_CUSTOMER_NAME));
            RepeatPojo repeatPojo2 = new RepeatPojo(BasicConstant.TWO, I18nMessageUtil.getMessage(BusinessConstant.REPEAT_CUSTOMER_PHONE));
            repeatTitles.add(repeatPojo1);

            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("corpid",corpid);
            map.put("del",DelEnum.NORMAL.getDel());
            map.put("saasMark", BasicConstant.ONE);
            // 只查询开启的表单
            map.put("enable",BasicConstant.ONE);
            map.put("businessType", XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
            List<PaasFormEntityExt> paasFormEntityList = paasFormModel.list(map);
            map.remove("orderByStr");
            //todo: 如果上面的 map 以后加入了 sort值排序，那么执行完上面的查询以后，记得要 map.remove("orderByStr");，因为map后面被复用了
            List<Long> formIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paasFormEntityList.forEach(item -> formIdIn.add(item.getId()));

            map.put("formIdIn", formIdIn);
            List<PaasFormExplainEntity> paasFormEntityExtList = paasFormExplainModel.list(map);
            for(PaasFormExplainEntity item : paasFormEntityExtList){
                if(Objects.nonNull(item) && Objects.equals(item.getDel(), DelEnum.NORMAL.getDel())) {
                    String explains = item.getExplains();
                    if(Objects.nonNull(explains)) {
                        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, null);
                        if(explainMap != null){
                            FieldAttrEntity fieldAttrEntity = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                            if(Objects.nonNull(fieldAttrEntity) && (Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ONE) && Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ONE))){
                                // 只要有客户一个表单模版电话字段可见，就加上电话字段模糊搜索
                                repeatTitles.add(repeatPojo2);
                                break;
                            }
                        }
                    }
                }
            }
        } else if(Objects.equals(businessType, XbbRefTypeEnum.CLUE.getCode())){
            RepeatPojo repeatPojo1 = new RepeatPojo(BasicConstant.ONE, I18nMessageUtil.getMessage(BusinessConstant.REPEAT_CLUE_NAME));
            RepeatPojo repeatPojo2 = new RepeatPojo(BasicConstant.TWO, I18nMessageUtil.getMessage(BusinessConstant.REPEAT_CLUE_PHONE));
            repeatTitles.add(repeatPojo1);

            Map<String,Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            map.put("corpid",corpid);
            map.put("del",DelEnum.NORMAL.getDel());
            map.put("saasMark", BasicConstant.ONE);
            // 只查询开启的表单
            map.put("enable",BasicConstant.ONE);
            map.put("businessType", XbbRefTypeEnum.CLUE.getCode());
            List<PaasFormEntityExt> paasFormEntityList = paasFormModel.list(map);
            map.remove("orderByStr");
            //todo: 如果上面的 map 以后加入了 sort值排序，那么执行完上面的查询以后，记得要 map.remove("orderByStr");，因为map后面被复用了
            List<Long> formIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            paasFormEntityList.forEach(item -> formIdIn.add(item.getId()));

            map.put("formIdIn", formIdIn);
            List<PaasFormExplainEntity> paasFormEntityExtList = paasFormExplainModel.list(map);
            for(PaasFormExplainEntity item : paasFormEntityExtList){
                if(Objects.nonNull(item) && Objects.equals(item.getDel(), DelEnum.NORMAL.getDel())) {
                    String explains = item.getExplains();
                    if(Objects.nonNull(explains)) {
                        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, null);
                        if(explainMap != null){
                            FieldAttrEntity fieldAttrEntity = explainMap.get(ClueEnum.PHONE.getAttr());
                            if(Objects.nonNull(fieldAttrEntity) && (Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ONE) && Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ONE))){
                                // 只要有一个表单模版电话字段可见，就加上电话字段模糊搜索
                                repeatTitles.add(repeatPojo2);
                                break;
                            }
                        }
                    }
                }
            }
        }
        repeatVO.setRepeatTitles(repeatTitles);
        return repeatVO;
    }


    /**
     * 客户和联系人查重渲染
     * @param customerRepeatDTO
     * @return
     */
    @Override
    public RecheckRepeatVO getRepeatMenu(CustomerRepeatDTO customerRepeatDTO) throws XbbException{
        RecheckRepeatVO recheckRepeatVO = new RecheckRepeatVO();
        List<RepeatInfo> repeatInfoList = new ArrayList<>();
        Integer businessType = customerRepeatDTO.getBusinessType();
        String corpid = customerRepeatDTO.getCorpid();
        try{
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
           param.put("enable", BasicConstant.ONE);
           param.put(StringConstant.CORPID, corpid);
           param.put("del", DelEnum.NORMAL.getDel());
           List<PaasMenuEntity> menuList = paasMenuModel.list(param);
           if(menuList == null){
               throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_EXIST);
           }
            UserVO loginUser = customerRepeatDTO.getLoginUser();
            Set<String> permissionAlias = loginUser.getPermSet();
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            switch(xbbRefTypeEnum){
                case CUSTOMER_MANAGEMENT:
                    boolean opportunityPermission = permissionAlias.contains(ProPermissionAliasEnum.SALES_OPPORTUNITY.getAlias())
                            && permissionAlias.contains(ProPermissionAliasEnum.OPPORTUNITY_DUPLICATE.getAlias())
                            && packageHelp.isUltimateWithFeeType(corpid);
                    //获得客户的所有已启用模版
                    List<PaasFormEntityExt> customerTemplateList = getTemplate(customerRepeatDTO, XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode());
                    //获得联系人的所有已启用模版
                    List<PaasFormEntityExt> contactTemplateList = getTemplate(customerRepeatDTO, XbbRefTypeEnum.CONTACT.getCode());
                    //机会
                    List<PaasFormEntityExt> opportunityTemplateList = getTemplate(customerRepeatDTO, XbbRefTypeEnum.SALES_OPPORTUNITY.getCode());
                    //去掉当前用户没有权限的表单
                    paasFormService.removeByPermission(opportunityTemplateList, customerRepeatDTO.getLoginUser());
                    menuList.forEach(item -> {
                        //客户
                        boolean customerFlag = permissionAlias.contains(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getAlias())
                                && permissionAlias.contains(XbbRefTypeEnum.CUSTOMER_DUPLICATE.getAlias())
                                && Objects.equals(item.getAlias(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getAlias())
                                && Objects.equals(BasicConstant.ZERO, item.getDistributorMark());
                        if(customerFlag){
                            //去掉当前用户没有权限的表单
                            paasFormService.removeByPermission(customerTemplateList, customerRepeatDTO.getLoginUser());
                            RepeatInfo repeatInfo = new RepeatInfo();
                            repeatInfo.setTitle(item.getName());
                            if(CollectionsUtil.isNotEmpty(customerTemplateList)){
                                repeatInfo.setFormId(customerTemplateList.get(0).getId());
                            }
                            repeatInfoList.add(repeatInfo);
                        }
                        //联系人
                        boolean contactFlag = permissionAlias.contains(XbbRefTypeEnum.CONTACT.getAlias())
                                && permissionAlias.contains(XbbRefTypeEnum.CONTACT_DUPLICATE.getAlias())
                                && Objects.equals(item.getAlias(), XbbRefTypeEnum.CONTACT.getAlias())
                                && Objects.equals(BasicConstant.ZERO, item.getDistributorMark());
                        if(contactFlag){
                            //去掉当前用户没有权限的表单
                            paasFormService.removeByPermission(contactTemplateList, customerRepeatDTO.getLoginUser());
                            RepeatInfo repeatInfo = new RepeatInfo();
                            repeatInfo.setTitle(item.getName());
                            if(CollectionsUtil.isNotEmpty(contactTemplateList)){
                                repeatInfo.setFormId(contactTemplateList.get(0).getId());
                            }
                            repeatInfoList.add(repeatInfo);
                        }
                        //机会
                        RepeatInfo repeatInfo = getOpportunityMobeilCheckTool(opportunityPermission, item, opportunityTemplateList);
                        if(Objects.nonNull(repeatInfo)){
                            repeatInfoList.add(repeatInfo);
                        }
                    });
                    break;
                case CLUE:
                    //获得线索的所有已启用模版
                    List<PaasFormEntityExt> clueTemplateList = getTemplate(customerRepeatDTO, XbbRefTypeEnum.CLUE.getCode());
                    menuList.forEach(item -> {
                        //客户
                        boolean customerFlag = permissionAlias.contains(XbbRefTypeEnum.CLUE.getAlias())
                                && permissionAlias.contains(XbbRefTypeEnum.CLUE_DUPLICATE.getAlias())
                                && Objects.equals(item.getAlias(), XbbRefTypeEnum.CLUE.getAlias())
                                && Objects.equals(BasicConstant.ZERO, item.getDistributorMark());
                        if(customerFlag){
                            //去掉当前用户没有权限的表单
                            paasFormService.removeByPermission(clueTemplateList, customerRepeatDTO.getLoginUser());
                            RepeatInfo repeatInfo = new RepeatInfo();
                            repeatInfo.setTitle(item.getName());
                            if(CollectionsUtil.isNotEmpty(clueTemplateList)){
                                repeatInfo.setFormId(clueTemplateList.get(0).getId());
                            }
                            repeatInfoList.add(repeatInfo);
                        }
                    });
                    break;
            }
            recheckRepeatVO.setRepeatInfo(repeatInfoList);
       }catch (Exception e){
            LOG.error("formDataService.getRepeatMenu 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
       }
        return recheckRepeatVO;
    }

    private RepeatInfo getOpportunityMobeilCheckTool(Boolean opportunityPermission,PaasMenuEntity menuEntity,List<PaasFormEntityExt> opportunityTemplateList){
       Boolean opportunityFlag  = opportunityPermission  && Objects.equals(menuEntity.getAlias(), XbbRefTypeEnum.SALES_OPPORTUNITY.getAlias())
                && Objects.equals(BasicConstant.ZERO, menuEntity.getDistributorMark());
        if(opportunityFlag){
            RepeatInfo repeatInfo = new RepeatInfo();
            repeatInfo.setTitle(menuEntity.getName());
            if(CollectionsUtil.isNotEmpty(opportunityTemplateList)){
                repeatInfo.setFormId(opportunityTemplateList.get(0).getId());
            }
            return repeatInfo;
        }
        return null;
    }


    private List<PaasFormEntityExt> getTemplate(CustomerRepeatDTO customerRepeatDTO, Integer businessType) throws XbbException{
        //获得客户的全部模版
        List<PaasFormEntityExt> paasFormEntityList = new ArrayList<>();
       try {
           Map<String, java.lang.Object> map = new HashMap<>();
           map.put("corpid", customerRepeatDTO.getCorpid());
           map.put("appId", customerRepeatDTO.getAppId());
           map.put("del", DelEnum.NORMAL.getDel());
           map.put("hidden", 0);
           map.put("businessType", businessType);
           map.put("enable", BasicConstant.ONE);
           map.remove("formId");
           paasFormEntityList = paasFormModel.list(map);
       }catch (Exception e){
           LOG.error("formDataService.getTemplate 出错：", e);
           throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, I18nStringConstant.TEMPLATE_NOT_EXIST);
       }
        return paasFormEntityList;
    }


    @Override
    public FormDataAddVO addBatch(FormDataAddDTO formDataSaveDTO) throws XbbException {
//        Map<String, Object> params = BeanUtil.convertBean2Map(formDataSaveDTO, true);
//        List<PaasFormExplainEntity> explainList = paasFormExplainModel.list(params);
//        if (Objects.isNull(explainList) || explainList.isEmpty()) {
//            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
//        }
//        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explainList.get(0).getExplains(), null);
        String corpid = formDataSaveDTO.getCorpid();

        if (!Objects.equals(formDataSaveDTO.getIsImport(), BasicConstant.ONE)) {
            //非导入时判断数据量限制
            Integer businessType = formDataSaveDTO.getBusinessType();
            XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            Integer oneStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.ONE_FORM_DATA_NUM, 1, xbbRefTypeEnum, formDataSaveDTO.getFormId());
            Integer allStatus = packageStatusHelp.getPackageStatus(corpid, ValueAddedTypeEnum.TOTAL_FORM_DATA_NUM, 1);
            if ( !Objects.equals(oneStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(oneStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.SINGLE_TABLE_NUM_LIMIT);
            }

            if ( !Objects.equals(allStatus, PackageStatusEnum.NORMAL.getCode()) && !Objects.equals(allStatus, PackageStatusEnum.WARNING.getCode()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100074, I18nStringConstant.TOTAL_TABLE_NUM_LIMIT);
            }
        }

        AddBatchDTO addBatchDTO;
        switch (RedundantTemplateTypeEnum.getByCode(formDataSaveDTO.getBusinessType())) {
            case PAYMENT:
                //只有在手动创建应收的模式下，才有新建的入口，所以在这边先加个校验
                Long nowModelType = fundSetService.getModelType(corpid,XbbRefTypeEnum.CRM);
                if (!Objects.equals(nowModelType, ModelTypeEnum.PLAN.getCode())) {
                    throw new XbbException(PaymentErrorCodeEnum.API_ERROR_208078);
                }
                formDataSaveDTO.setIsTotalPaymentSheetAmount(true);
                addBatchDTO = paymentService.beforeSaveBatch(formDataSaveDTO, false);
                break;
            case PAY_PLAN:
                formDataSaveDTO.setIsTotalPaymentSheetAmount(true);
                addBatchDTO = payPlanService.beforeSaveBatch(formDataSaveDTO, false);
                break;
            default:
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }

//        for (ValidateDataDTO validateDataDTO : addBatchDTO.getValidateDataDTOList()) {
//            validateDataDTO.setExplainMap(explainMap);
//            formDataValidateDataHelp.validateData(validateDataDTO);
//            ProSaveHelp.analyticalData(validateDataDTO);
//        }
        FormDataAddVO formDataAddVO;
        switch (RedundantTemplateTypeEnum.getByCode(formDataSaveDTO.getBusinessType())) {
            case PAYMENT:
                PaymentDTO paymentDTO = new PaymentDTO();
                BeanUtil.copyProperties(addBatchDTO, paymentDTO);
                formDataAddVO = paymentService.pay(paymentDTO);
                break;
            case PAY_PLAN:
                PayPlanDTO payPlanDTO = new PayPlanDTO();
                BeanUtil.copyProperties(addBatchDTO, payPlanDTO);
                formDataAddVO = payPlanService.payPlan(payPlanDTO);
                break;
            default:
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return formDataAddVO;
    }

    @Override
    public DefaultOwnerAndCoUserGetVO getDefaultOwnerAndCoUser(DefaultOwnerAndCoUserGetDTO defaultOwnerAndCoUserGetDTO) throws XbbException {
        Integer businessType = defaultOwnerAndCoUserGetDTO.getBusinessType();
        businessType = XbbRefTypeEnum.transferBusinessType4Distributor(businessType,defaultOwnerAndCoUserGetDTO.getDistributorMark());
        //红冲应收款本质是应收款，转换一下
        businessType = Objects.equals(businessType, XbbRefTypeEnum.RED_RECEIVABLES.getCode()) ? XbbRefTypeEnum.PAYMENT.getCode() : businessType;
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        List<Long> selectDataIdList = defaultOwnerAndCoUserGetDTO.getSelectDataIdList();
        String corpid = defaultOwnerAndCoUserGetDTO.getCorpid();
        Integer saasMark = defaultOwnerAndCoUserGetDTO.getSaasMark();
        Integer distributorMark = defaultOwnerAndCoUserGetDTO.getDistributorMark();
        //上游业务类型
        Integer selectBusinessType = defaultOwnerAndCoUserGetDTO.getSelectBusinessType();
        DefaultOwnerAndCoUserGetVO defaultOwnerAndCoUserGetVO = new DefaultOwnerAndCoUserGetVO();
        //经销商业务（订货单、退货单）  不参与团队继承处理（走以前的逻辑）
        if(Objects.equals(distributorMark, DistributorMarkEnum.DISTRIBUTOR.getCode()) && (Objects.equals(businessType,XbbRefTypeEnum.ORDER.getCode()) || Objects.equals(businessType,XbbRefTypeEnum.RETURN.getCode()))){
            switch (xbbRefTypeEnum) {
                case ORDER:
                case RETURN:
                    selectBusinessType = XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode();
                    break;
                default:
                    throw new XbbException(TemplateErrorCodeEnum.API_ERROR_350006);
            }
            return getMainAndCoUser(businessType,selectBusinessType,selectDataIdList,corpid,distributorMark);
        }
        //预收款、预付款默认继承，直接回显
        if(Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PREPAYMENT)
                || Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.PREPAY)
                || Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.RED_PREPAY)
                || Objects.equals(xbbRefTypeEnum,XbbRefTypeEnum.RED_PREPAYMENT)){
            return getMainAndCoUser(businessType,selectBusinessType,selectDataIdList,corpid,distributorMark);
        }


        XbbRefTypeEnum linkXbbRefType = XbbRefTypeEnum.getByCode(selectBusinessType);
        //团队成员回显到页面上
        Map<String, Object> params = new HashMap<>();
        params.put(ParameterConstant.CORPID, corpid);
        params.put(ParameterConstant.ID_IN, selectDataIdList);
        List<Long> formIds = new ArrayList<>();
        //需要一个上游业务的 formId->dataIds 的一个集合
        //下面要根据formId查询继承列表，然后根据dataIds获取回显团队
        Map<Long, List<Long>> formDataMap = new HashMap<>();
        switch(linkXbbRefType){
            case CUSTOMER_MANAGEMENT:
                List<CustomerEntityExt> customerEntitys = customerModel.findEntitys(params);
                for (CustomerEntityExt entity : customerEntitys) {
                    Long formId = entity.getFormId();
                    Long dataId = entity.getId();
                    if(Objects.isNull(formDataMap.get(formId))){
                        List<Long> dataIds = new ArrayList<>();
                        dataIds.add(dataId);
                        formDataMap.put(formId,dataIds);
                    } else{
                        formDataMap.get(formId).add(dataId);
                    }
                }
                formIds = customerEntitys.stream().map(CustomerEntityExt::getFormId).collect(Collectors.toList());
                break;
            case SALES_OPPORTUNITY:
                List<OpportunityEntityExt> opportunityEntitys = opportunityModel.findEntitys(params);
                for (OpportunityEntityExt entity : opportunityEntitys) {
                    Long formId = entity.getFormId();
                    Long dataId = entity.getId();
                    if(Objects.isNull(formDataMap.get(formId))){
                        List<Long> dataIds = new ArrayList<>();
                        dataIds.add(dataId);
                        formDataMap.put(formId,dataIds);
                    } else{
                        formDataMap.get(formId).add(dataId);
                    }
                }
                formIds = opportunityEntitys.stream().map(OpportunityEntityExt::getFormId).collect(Collectors.toList());
                break;
            case CONTRACT:
                List<ContractEntityExt> contractEntitys = contractModel.findEntitys(params);
                for (ContractEntityExt entity : contractEntitys) {
                    Long formId = entity.getFormId();
                    Long dataId = entity.getId();
                    if(Objects.isNull(formDataMap.get(formId))){
                        List<Long> dataIds = new ArrayList<>();
                        dataIds.add(dataId);
                        formDataMap.put(formId,dataIds);
                    }else{
                        formDataMap.get(formId).add(dataId);
                    }
                }
                formIds = contractEntitys.stream().map(ContractEntityExt::getFormId).collect(Collectors.toList());
                break;
            case PAY_PLAN:
                List<PayPlanEntityExt> payPlanEntitys = payPlanModel.findEntitys(params);
                for (PayPlanEntityExt entity : payPlanEntitys) {
                    Long formId = entity.getFormId();
                    Long dataId = entity.getId();
                    if(Objects.isNull(formDataMap.get(formId))){
                        List<Long> dataIds = new ArrayList<>();
                        dataIds.add(dataId);
                        formDataMap.put(formId,dataIds);
                    } else{
                        formDataMap.get(formId).add(dataId);
                    }
                }
                formIds = payPlanEntitys.stream().map(PayPlanEntityExt::getFormId).collect(Collectors.toList());
                break;
            case SUPPLIER:
                List<SupplierEntityExt> supplierEntitys = supplierModel.findEntitys(params);
                for (SupplierEntityExt entity : supplierEntitys) {
                    Long formId = entity.getFormId();
                    Long dataId = entity.getId();
                    if(Objects.isNull(formDataMap.get(formId))){
                        List<Long> dataIds = new ArrayList<>();
                        dataIds.add(dataId);
                        formDataMap.put(formId,dataIds);
                    } else{
                        formDataMap.get(formId).add(dataId);
                    }
                }
                formIds = supplierEntitys.stream().map(SupplierEntityExt::getFormId).collect(Collectors.toList());
                break;
            case PURCHASE:
                List<PurchaseEntityExt> purchaseEntitys = purchaseModel.findEntitys(params);
                for (PurchaseEntityExt entity : purchaseEntitys) {
                    Long formId = entity.getFormId();
                    Long dataId = entity.getId();
                    if(Objects.isNull(formDataMap.get(formId))){
                        List<Long> dataIds = new ArrayList<>();
                        dataIds.add(dataId);
                        formDataMap.put(formId,dataIds);
                    } else{
                        formDataMap.get(formId).add(dataId);
                    }
                }
                formIds = purchaseEntitys.stream().map(PurchaseEntityExt::getFormId).collect(Collectors.toList());
                break;
            case MARKET_ACTIVITY:
                List<MarketActivityEntityExt> marketActivityEntitys = marketActivityModel.findEntitys(params);
                for (MarketActivityEntityExt entity : marketActivityEntitys) {
                    Long formId = entity.getFormId();
                    Long dataId = entity.getId();
                    if(Objects.isNull(formDataMap.get(formId))){
                        List<Long> dataIds = new ArrayList<>();
                        dataIds.add(dataId);
                        formDataMap.put(formId,dataIds);
                    } else{
                        formDataMap.get(formId).add(dataId);
                    }
                }
                formIds = marketActivityEntitys.stream().map(MarketActivityEntityExt::getFormId).collect(Collectors.toList());
                break;
            case CLUE:
                List<ClueEntityExt> clueEntitys = clueModel.findEntitys(params);
                for (ClueEntityExt entity : clueEntitys) {
                    Long formId = entity.getFormId();
                    Long dataId = entity.getId();
                    if(Objects.isNull(formDataMap.get(formId))){
                        List<Long> dataIds = new ArrayList<>();
                        dataIds.add(dataId);
                        formDataMap.put(formId,dataIds);
                    } else{
                        formDataMap.get(formId).add(dataId);
                    }
                }
                formIds = clueEntitys.stream().map(ClueEntityExt::getFormId).collect(Collectors.toList());
                break;
            default:
                break;
        }

        //根据dataId和业务类型获取上游的formId，然后根据formId获取其继承列表，若此新建业务在继承关系内，则回显团队
        List<FormTeamSetEntity> formTeamSetList = formTeamSetHelp.getFormTeamSetList(corpid, formIds, saasMark, selectBusinessType, distributorMark);
        Map<Long, FormTeamSetEntity> formTeamSetMap = formTeamSetList.stream().collect(Collectors.toMap(FormTeamSetEntity::getFormId, v -> v, (v1, v2) -> v2));
        for (Map.Entry<Long, List<Long>> longListEntry : formDataMap.entrySet()) {
            Long formId = longListEntry.getKey();
            FormTeamSetEntity formTeamSet = formTeamSetMap.get(formId);
            List<Long> dataIds = longListEntry.getValue();
            if(Objects.isNull(formTeamSet)){
                continue;
            }
            if(Objects.equals(formTeamSet.getModel(),FormPatternEnum.FORM_SHARE.getModel())){
                List<TeamLinkPOJO> linkListPojos = JSON.parseArray(JSON.toJSONString(formTeamSet.getLinkForm()), TeamLinkPOJO.class);
                Set<Integer> collect = linkListPojos.stream().map(TeamLinkPOJO::getLinkBusinessType).collect(Collectors.toSet());
                //回款单、付款单特殊处理
                //如果是预收、预付类型的，默认继承，其余类型的，则关联了才回显
                if(PaymentSheetTypeEnum.getAllBusinessType().contains(businessType)){
                    if(PaymentSheetTypeEnum.getBusinessTypeExcludePre().contains(businessType)){
                        //非预收类型的，走继承关系
                        businessType = XbbRefTypeEnum.PAYMENT_SHEET.getCode();
                    }else{
                        return getMainAndCoUser(businessType,selectBusinessType,dataIds,corpid,distributorMark);
                    }

                }else if(PaySheetTypeEnum.getAllBusinessType().contains(businessType)){
                    if(PaySheetTypeEnum.getBusinessTypeExcludePre().contains(businessType)){
                        //非预付类型的，走继承关系
                        businessType = XbbRefTypeEnum.PAY_SHEET.getCode();
                    }else{
                        return getMainAndCoUser(businessType,selectBusinessType,dataIds,corpid,distributorMark);
                    }

                }

                if(collect.contains(businessType)){
                    //上游业务关联了当前业务，需要继承团队
                    if(CollectionUtils.isEmpty(defaultOwnerAndCoUserGetVO.getOwnerList())
                            &&CollectionUtils.isEmpty(defaultOwnerAndCoUserGetVO.getCoUserList())
                            &&CollectionUtils.isEmpty(defaultOwnerAndCoUserGetVO.getSignUserList())){
                        defaultOwnerAndCoUserGetVO = getMainAndCoUser(businessType,selectBusinessType,dataIds,corpid,distributorMark);
                    }else{
                        //需要聚合团队，因为传了多个dataId
                        DefaultOwnerAndCoUserGetVO newDefaultOwnerAndCoUserGetVO = getMainAndCoUser(businessType, selectBusinessType, dataIds, corpid, distributorMark);
                        mergeMainAndCoUser(defaultOwnerAndCoUserGetVO,newDefaultOwnerAndCoUserGetVO);
                    }
                }
            }else{
                //隔离不用回显团队

            }
        }
        return defaultOwnerAndCoUserGetVO;
    }

    /**
     *
     * @Description: 联合新建的时候，返回继承规则，用于前端反显下游业务的团队
     * @param
     * @return: com.xbongbong.pro.formdata.pojo.vo.InheritRuleVO
     * @Author: shen.yang
     * @Date: 2022/6/6  11:05
    */
    @Override
    public InheritRuleVO getInheritRule(InheritRuleDTO inheritRuleDTO) throws XbbException {
        InheritRuleVO inheritRuleVO = new InheritRuleVO();
        Integer businessType = inheritRuleDTO.getBusinessType();
        if(Objects.isNull(inheritRuleDTO.getFormId())){
            if(Objects.isNull(inheritRuleDTO.getDataId())){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018.getCode(), I18nStringConstant.FORM_NOT_EXIST);
            }else{
                List<PaasFormDataEntityExt> byDataIdList = formDataHelp.getByDataIdList(Collections.singletonList(inheritRuleDTO.getDataId()), inheritRuleDTO.getBusinessType(), inheritRuleDTO.getSaasMark(), null, inheritRuleDTO.getCorpid());
                if(CollectionUtils.isEmpty(byDataIdList)){
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100018.getCode(), I18nStringConstant.FORM_NOT_EXIST);
                }
                inheritRuleDTO.setFormId(byDataIdList.get(Constant.ZERO).getFormId());
            }
        }
        inheritRuleVO.setFormId(inheritRuleDTO.getFormId());
        FormTeamSetEntity formTeamSet = formTeamSetHelp.getFormTeamSet(inheritRuleDTO.getCorpid(), inheritRuleDTO.getFormId(), inheritRuleDTO.getSaasMark(), inheritRuleDTO.getBusinessType(), inheritRuleDTO.getDistributorMark());
        List<LinkListPojo> linkListPojos = JSON.parseArray(JSON.toJSONString(formTeamSet.getLinkForm()), LinkListPojo.class);
        Set<Integer> linkList;
        if(CollectionUtils.isNotEmpty(linkListPojos)){
            linkList = linkListPojos.stream().map(LinkListPojo::getLinkBusinessType).collect(Collectors.toSet());
        }else{
            linkList = new HashSet<>();
        }
        inheritRuleVO.setLinkList(linkList);
        //隔离或者继承列表为空，则不用判断继承关系，加个flag简化前端操作
        if(Objects.equals(formTeamSet.getModel(),FormPatternEnum.FORM_ISOLATION.getModel()) || CollectionUtils.isEmpty(linkList)){
            inheritRuleVO.setInheritFlag(false);
            //如果是客户或者供应商，有默认关联，不能直接给false，过滤一下
            if(Objects.equals(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), businessType) || Objects.equals(XbbRefTypeEnum.SUPPLIER.getCode(), businessType) ){
                inheritRuleVO.setInheritFlag(true);
                //但是只能给默认继承列表，清空当前列表即可
                linkList.clear();
            }
        }else{
            inheritRuleVO.setInheritFlag(true);
        }
        //付款单、回款单和应收款需要聚合子业务类型
        if(CollectionUtils.isNotEmpty(linkList)){
            if(linkList.contains(XbbRefTypeEnum.PAYMENT_SHEET.getCode())){
                linkList.addAll(PaymentSheetTypeEnum.getBusinessTypeExcludePre());
            }else if(linkList.contains(XbbRefTypeEnum.PAY_SHEET.getCode())){
                linkList.addAll(PaySheetTypeEnum.getBusinessTypeExcludePre());
            }else if(linkList.contains(XbbRefTypeEnum.PAYMENT.getCode())){
                linkList.add(XbbRefTypeEnum.RED_RECEIVABLES.getCode());
            }
        }
        //客户、经销商和共供应商有预收预付的默认关联需要加上
        if(Objects.equals(inheritRuleDTO.getBusinessType(), XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())
                || Objects.equals(inheritRuleDTO.getBusinessType(), XbbRefTypeEnum.DISTRIBUTOR_MANAGEMENT.getCode())){
            linkList.add(XbbRefTypeEnum.PREPAYMENT.getCode());
            linkList.add(XbbRefTypeEnum.RED_PREPAYMENT.getCode());
        }else if(Objects.equals(inheritRuleDTO.getBusinessType(), XbbRefTypeEnum.SUPPLIER.getCode())){
            linkList.add(XbbRefTypeEnum.PREPAY.getCode());
            linkList.add(XbbRefTypeEnum.RED_PREPAY.getCode());
        }
        return inheritRuleVO;
    }


    /**
     *
     * @Description: 新建页回显团队公共方法
     * @param businessType 新建业务类型
     * @param selectBusinessType 上游业务类型
     * @param selectDataIds 上游业务数据id集合
     * @param corpid 公司id
     * @param distributorMark 经销商标识
     * @return: com.xbongbong.pro.formdata.pojo.vo.DefaultOwnerAndCoUserGetVO
     * @Author: shen.yang
     * @Date: 2022/3/3  19:48
    */
    private DefaultOwnerAndCoUserGetVO getMainAndCoUser(Integer businessType, Integer selectBusinessType, List<Long> selectDataIds, String corpid, Integer distributorMark){
        DefaultOwnerAndCoUserGetVO defaultOwnerAndCoUserGetVO = new DefaultOwnerAndCoUserGetVO();
        Map<Long, List<String>> mainUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Map<Long, List<String>> coUserMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userTeamService.getUserIdMap(selectDataIds, corpid, selectBusinessType, false, mainUserMap, coUserMap);
        Set<String> mainUserList =  new HashSet<>();
        Set<String> coUserList =  new HashSet<>();
        for (Long selectDataId : selectDataIds) {
            mainUserList.addAll(mainUserMap.getOrDefault(selectDataId,new ArrayList<>()));
            coUserList.addAll(coUserMap.getOrDefault(selectDataId,new ArrayList<>()));
        }
        Set<String> userIdIn = new HashSet<>();
        userIdIn.addAll(mainUserList);
        userIdIn.addAll(coUserList);
        List<UserEntity> userEntityList = userModel.getByUserIdIn(corpid, userIdIn, true);
        Map<String, UserEntity> userEntityMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        userEntityList.forEach(user -> userEntityMap.put(user.getUserId(), user));
        List<ReturnUserAndDepartmentPojo> ownerPojoList = new ArrayList<>();
        ReturnUserAndDepartmentPojo returnUserAndDepartmentPojo;
        List<ReturnUserAndDepartmentPojo> coUserPojoList = new ArrayList<>();
        UserEntity user;
        for ( String userId : mainUserList ) {
            returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
            user = userEntityMap.get(userId);
            if ( Objects.nonNull(user) ) {
                BeanUtil.copyProperties(user, returnUserAndDepartmentPojo);
                returnUserAndDepartmentPojo.setId(user.getUserId());
                ownerPojoList.add(returnUserAndDepartmentPojo);
            }
        }
        for ( String userId : coUserList ) {
            returnUserAndDepartmentPojo = new ReturnUserAndDepartmentPojo();
            user = userEntityMap.get(userId);
            if ( Objects.nonNull(user) ) {
                BeanUtil.copyProperties(user, returnUserAndDepartmentPojo);
                returnUserAndDepartmentPojo.setId(user.getUserId());
                coUserPojoList.add(returnUserAndDepartmentPojo);
            }
        }
        defaultOwnerAndCoUserGetVO.setOwnerList(ownerPojoList);
        defaultOwnerAndCoUserGetVO.setCoUserList(coUserPojoList);
        //订货单 退货单 还需要返回签订人
        if ((Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(),businessType) || Objects.equals(XbbRefTypeEnum.REFUND.getCode(),businessType)) && Objects.equals(DistributorMarkEnum.DISTRIBUTOR.getCode(),distributorMark)){
            if(Objects.nonNull(ownerPojoList) && ownerPojoList.size() > 0) {
                List<ReturnUserAndDepartmentPojoExt> signList = new ArrayList<>();
                ReturnUserAndDepartmentPojo userAndDepartmentPojo = ownerPojoList.get(0);
                ReturnUserAndDepartmentPojoExt returnUserAndDepartmentPojoExt = new ReturnUserAndDepartmentPojoExt();
                BeanUtil.copyProperties(userAndDepartmentPojo,returnUserAndDepartmentPojoExt);
                if (Objects.equals(XbbRefTypeEnum.CONTRACT.getCode(),businessType)){
                    returnUserAndDepartmentPojoExt.setAttr(ContractEnum.SIGN_PERSON.getAttr());
                    // 订货单带默认收货人信息
                    Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    param.put("corpid", corpid);
                    param.put("dataIdIn", selectDataIds);
                    param.put("del", DelEnum.NORMAL.getDel());
                    List<CustomerSubDataEntity> entitys = customerSubDataModel.findEntitys(param);
                    if (Objects.nonNull(entitys)) {
                        for (PaasFormSubDataEntity entity : entitys) {
                            if (Objects.equals(DistributorEnum.SHIPPING_ADDRESS.getAttr(), entity.getAttr())) {
                                Object isDefaultAddress = entity.getData().get("num_1");
                                if (Objects.equals(isDefaultAddress,BasicConstant.ONE)){
                                    // 前端渲染需要暂时写死
                                    entity.getData().put("attr", OrderEnum.LINK_PARTNER_RECEIVER.getAttr());
                                    entity.getData().put("name",entity.getData().get(DistributorAddressEnum.RECEIVER.getAttr()));
                                    entity.getData().put("id",entity.getId());
                                    defaultOwnerAndCoUserGetVO.setDefaultAddress(entity);
                                    break;
                                }
                            }
                        }
                    }

                }else {
                    returnUserAndDepartmentPojoExt.setAttr(ReturnEnum.SIGN_USER.getAttr());
                }
                signList.add(returnUserAndDepartmentPojoExt);
                defaultOwnerAndCoUserGetVO.setSignUserList(signList);
            }
        }
        return defaultOwnerAndCoUserGetVO;
    }
    /**
     *
     * @Description: 多个dataId对应多个团队，需要聚合再返给前端
     * @param oldVO 之前的dataId聚合生成的VO
     * @param newVO 新dataId生成的VO
     * @return: com.xbongbong.pro.formdata.pojo.vo.DefaultOwnerAndCoUserGetVO
     * @Author: shen.yang
     * @Date: 2022/3/4  17:05
    */
    private DefaultOwnerAndCoUserGetVO mergeMainAndCoUser(DefaultOwnerAndCoUserGetVO oldVO, DefaultOwnerAndCoUserGetVO newVO){
        //只需要做聚合ownerList 和 coUserList
        List<ReturnUserAndDepartmentPojo> oldOwnerList = oldVO.getOwnerList();
        List<Object> oldOwnerIdList = oldOwnerList.stream().map(ReturnUserAndDepartmentPojo::getId).collect(Collectors.toList());
        List<ReturnUserAndDepartmentPojo> oldCoUserList = oldVO.getCoUserList();
        List<ReturnUserAndDepartmentPojo> newOwnerList = newVO.getOwnerList();
        Map<Object, ReturnUserAndDepartmentPojo> newOwnerMap = newOwnerList.stream().collect(Collectors.toMap(ReturnUserAndDepartmentPojo::getId, v -> v));
        List<ReturnUserAndDepartmentPojo> newCoUserList = newVO.getCoUserList();
        Set<Object> mixOwnerIdList = new HashSet<>();
        mixOwnerIdList.addAll(oldOwnerList.stream().map(ReturnUserAndDepartmentPojo::getId).collect(Collectors.toList()));
        mixOwnerIdList.addAll(newOwnerList.stream().map(ReturnUserAndDepartmentPojo::getId).collect(Collectors.toList()));
        Set<Object> mixCoUserIdList = new HashSet<>();
        mixCoUserIdList.addAll(oldCoUserList.stream().map(ReturnUserAndDepartmentPojo::getId).collect(Collectors.toList()));
        mixCoUserIdList.addAll(newCoUserList.stream().map(ReturnUserAndDepartmentPojo::getId).collect(Collectors.toList()));
        //在某团队中为负责人，另一个团队中为协同人的，聚合之后为负责人
        for (Object ownerId : mixOwnerIdList) {
            if(!oldOwnerIdList.contains(ownerId)){
                oldOwnerList.add(newOwnerMap.get(ownerId));
            }
        }
        mixCoUserIdList.removeIf(mixOwnerIdList::contains);
        //过滤掉协同人团队里的负责人 (不用做负责人和协同人的互相去重，留给客户自己主动删除)
        //List<ReturnUserAndDepartmentPojo> mixCoUserList = Streams.concat(oldCoUserList.stream(), newCoUserList.stream()).filter(v -> mixCoUserIdList.contains(v.getId())).collect(Collectors.toList());
        //oldVO.setCoUserList(mixCoUserList);
        return oldVO;
    }

    /**
     * saas特殊列表页处理
     * 有列表无表单设计入口
     *
     * @param explainList     字段解释
     * @param formDataListDTO 参数
     */
    @Override
    public void handelSaasSpecialList(List<FieldAttrEntity> explainList, FormDataListDTO formDataListDTO) {
        SaasSpecialListEnum saasSpecialListEnum = SaasSpecialListEnum.getByBusinessType(formDataListDTO.getSubBusinessType());
        Iterator<FieldAttrEntity> iterator = explainList.iterator();
        switch (saasSpecialListEnum) {
            case CUSTOMER:
            case CUSTOMER_DEAL:
            case CUSTOMER_FOLLOW:
            case CUSTOMER_FOCUS:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if ( Objects.equals(attr, CustomerManagementEnum.BACK_PUBLIC_DATE.getAttr()) ) {
                        iterator.remove();
                        break;
                    }
                }
                break;
            case CUSTOMER_PUBLIC:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if ( Objects.equals(attr, CustomerManagementEnum.DISTRIBUTION_DATE.getAttr()) || Objects.equals(attr, CustomerManagementEnum.COUSERID.getAttr()) ) {
                        iterator.remove();
                    }
                    if ( Objects.equals(attr, CustomerManagementEnum.OWNER_ID.getAttr()) ) {
                        fieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.PRE_OWNER_ID));
                    }
                }
                break;
            case CUSTOMER_RECYCLE:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if ( Objects.equals(attr, CustomerManagementEnum.BACK_PUBLIC_DATE.getAttr()) || Objects.equals(attr, CustomerManagementEnum.DISTRIBUTION_DATE.getAttr())
                            || Objects.equals(attr, CustomerManagementEnum.OWNER_ID.getAttr()) || Objects.equals(attr, CustomerManagementEnum.COUSERID.getAttr()) ) {
                        iterator.remove();
                    }
                }
                break;
            case WAITINSTOCK:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if ( !(Objects.equals(attr, PurchaseEnum.SHEET_NO.getAttr())
                            || Objects.equals(attr, PurchaseEnum.PURCHASE_NAME.getAttr())
                            || Objects.equals(attr, PurchaseEnum.STATUS.getAttr())
                            || Objects.equals(attr, PurchaseEnum.SIGNER_ID.getAttr())
                            || Objects.equals(attr, FieldTypeEnum.ADDTIME.getAlias())) ) {
                        iterator.remove();
                    }
                }
                break;
            case WAITOUTSTOCK:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if ( !(Objects.equals(attr, ContractEnum.NAME.getAttr())
                            || Objects.equals(attr, ContractEnum.CONTRACT_NO.getAttr())
                            || Objects.equals(attr, ContractEnum.STATUS.getAttr())
                            || Objects.equals(attr, ContractEnum.SIGN_TIME.getAttr())
                            || Objects.equals(attr, ContractEnum.MINOR_USER.getAttr())
                            || Objects.equals(attr, FieldTypeEnum.ADDTIME.getAlias())
                            || Objects.equals(attr, FieldTypeEnum.UPDATETIME.getAlias())
                            || Objects.equals(attr, FieldTypeEnum.CREATORID.getAlias())) ) {
                        iterator.remove();
                    }
                }
                break;
            case WAITPURCHASE:
            case WAITPRODUCE:
                if ( Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.CONTRACT.getCode()) ) {
                    while (iterator.hasNext()) {
                        FieldAttrEntity fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if ( !(Objects.equals(attr, ContractEnum.NAME.getAttr())
                                || Objects.equals(attr, ContractEnum.LINK_CUSTOMER.getAttr())
                                || Objects.equals(attr, ContractEnum.CONTRACT_NO.getAttr())
                                || Objects.equals(attr, FieldTypeEnum.ADDTIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.UPDATETIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.CREATORID.getAlias())) ) {
                            iterator.remove();
                        }
                    }
                } else if ( Objects.equals(formDataListDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode()) ) {
                    while (iterator.hasNext()) {
                        FieldAttrEntity fieldAttrEntity = iterator.next();
                        String attr = fieldAttrEntity.getAttr();
                        if ( Objects.equals(attr, ProductEnum.STOCK.getAttr()) ) {
                            fieldAttrEntity.setAttrName(I18nMessageUtil.getMessage(I18nStringConstant.OUT_OF_STOCK_NUM));
                        } else if ( !(Objects.equals(attr, ProductEnum.NAME.getAttr())
                                || Objects.equals(attr, ProductEnum.PRODUCT_IMGS.getAttr())
                                || Objects.equals(attr, ProductEnum.SPECIFICATION.getAttr())
                                || Objects.equals(attr, ProductEnum.UNIT.getAttr())
                                || Objects.equals(attr, ProductEnum.SUPPLIER.getAttr())
                                || Objects.equals(attr, FieldTypeEnum.ADDTIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.UPDATETIME.getAlias())
                                || Objects.equals(attr, FieldTypeEnum.CREATORID.getAlias())) ) {
                            iterator.remove();
                        }
                    }
                }
                break;
            case WORKORDER:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if ( !(Objects.equals(attr, WorkOrderEnum.SHEET_NO.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.SERVICE_PRICE.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.EMERGENCY_LEVEL.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.ADD_TIME.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.IMPLEMENTATION_TIME.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.UPDATE_TIME.getAttr())) ) {
                        iterator.remove();
                    }
                }
                break;
            case WORK_ORDER_ROB:
                while (iterator.hasNext()) {
                    FieldAttrEntity fieldAttrEntity = iterator.next();
                    String attr = fieldAttrEntity.getAttr();
                    if ( !(Objects.equals(attr, WorkOrderEnum.SHEET_NO.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.SERVICE_PRICE.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.EMERGENCY_LEVEL.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.ADD_TIME.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.IMPLEMENTATION_TIME.getAttr())
                            || Objects.equals(attr, WorkOrderEnum.UPDATE_TIME.getAttr())) ) {
                        iterator.remove();
                    }
                }
                break;
            default:
                break;
        }
    }

    @Override
    public DefaultDataVO getDafaultData(DefaultDataDTO businessDataDTO) throws XbbException {
        DefaultDataVO defaultDataVO = new DefaultDataVO();
        try {
            String corpid = businessDataDTO.getCorpid();
            Integer businessType = businessDataDTO.getBusinessType();
            Integer saasMark = businessDataDTO.getSaasMark();
            Long formId = businessDataDTO.getFormId();
            PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
            List<PaasFormDataEntityExt> paasFormDataList = new ArrayList<>();
            if ( !Objects.equals(businessType, XbbRefTypeEnum.WORK_ORDER.getCode()) && Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) ) {
                paasFormExplainEntity = paasFormExplainModel.getByFormId(formId, corpid);
                List<Long> dataIdIn = businessDataDTO.getIdIn();
                if ( dataIdIn != null && !dataIdIn.isEmpty() ) {
                    IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, businessType, saasMark);
                    paasFormDataList = paasEsModel.getByIdList(dataIdIn, corpid, saasMark, businessType, new ArrayList<>(), indexTypeEnum);
                }
            }
            if ( paasFormExplainEntity == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
            }
            if ( paasFormDataList.isEmpty() ) {
                return new DefaultDataVO();
            }
            List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            PaasFormEntityExt paasFormEntity = paasFormModel.getByKey(paasFormExplainEntity.getFormId(),corpid);
            for (FieldAttrEntity fieldAttrEntity : explainList) {
                proFormHelp.setItem(fieldAttrEntity,paasFormEntity);
                explainMap.put(fieldAttrEntity.getAttr(),fieldAttrEntity);
            }
            RedundantTemplateTypeEnum byCode = RedundantTemplateTypeEnum.getByCode(businessType);
            switch (byCode) {
                case QUOTATION:
                    PaasFormDataEntityExt quotationEntity = paasFormDataList.get(0);
                    defaultDataVO = quotationService.getQuotationDefault(businessDataDTO, explainMap, quotationEntity);
                    break;
                case SALES_OPPORTUNITY:
                    PaasFormDataEntityExt oppEntity = paasFormDataList.get(0);
                    defaultDataVO = opportunityService.getOppDefault(businessDataDTO, explainMap, oppEntity);
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            LOG.error("formDataService.getDafaultData 出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return defaultDataVO;
    }

    @Override
    public BusinessCustomerListRelyVO businessCusomerListGetRely(BussinessCustomerListRelyDTO bussinessCustomerListRelyDTO) throws XbbException{
        BusinessCustomerListRelyVO businessCustomerListRelyVO= new BusinessCustomerListRelyVO();
        try {
            String corpid = bussinessCustomerListRelyDTO.getCorpid();
            Long dataId = bussinessCustomerListRelyDTO.getDataId();
            Integer businessType = bussinessCustomerListRelyDTO.getBusinessType();
            PaasFormExplainEntity paasFormExplain = paasFormExplainModel.getByBusinessType(businessType,corpid);
            Map<String,FieldAttrEntity> expMap = ExplainUtil.getExplainMap(paasFormExplain.getExplains());
            JSONObject json =new JSONObject();
            XbbRefTypeEnum xbbRefTypeEnum=XbbRefTypeEnum.getByCode(bussinessCustomerListRelyDTO.getBusinessType());
            switch (xbbRefTypeEnum){
                case CONTRACT_OUTSTOCK:
                     Map<String,Object> param=new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                     param.put("corpid",corpid);
                     param.put("id",dataId);
                     param.put("del",0);
                     List<CustomerEntityExt> customerEntityExts = customerModel.findEntitys(param);
                     Long formId = null;
                     for (CustomerEntityExt entity : customerEntityExts) {
                         formId = entity.getFormId();
                         JSONObject data = entity.getData();
                         // todo 已知有两处 后面提取出来 A B 表单下拉选项uuid不上
                         JSONArray jsonArray =  data.getJSONArray(CustomerManagementEnum.PHONE.getAttr());
                         FieldAttrEntity fieldAttrEntity = expMap.getOrDefault(ContractOutstockEnum.CUSTOMER_PHONE.getAttr(),new FieldAttrEntity());
                         if (Objects.isNull(fieldAttrEntity.getSubForm()) || Objects.isNull(fieldAttrEntity.getSubForm().getItems())){
                             throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
                         }
                         List<FieldAttrEntity> subExplainList = JSONArray.parseArray(JSON.toJSONString(fieldAttrEntity.getSubForm().getItems()), FieldAttrEntity.class);
                         Map<String,FieldAttrEntity> map = ExplainUtil.getExplainMapByList(subExplainList,"text_1");
                         FieldAttrEntity entityType = map.get("text_1");
                         if (Objects.nonNull(entity)){
                             List<ItemPoJo> poJoList = entityType.getItems();
                             if (Objects.nonNull(jsonArray)){
                                 for (int i = 0; i < jsonArray.size(); i++) {
                                     JSONObject jsonObject = jsonArray.getJSONObject(i);
                                     if (Objects.nonNull(jsonObject)){
                                         String value = jsonObject.getString("text_1");
                                         boolean exist = false;
                                         if (Objects.nonNull(poJoList)){
                                             for (int j = 0; j < poJoList.size(); j++) {
                                                 ItemPoJo  itemPoJo = poJoList.get(j);
                                                 if (Objects.equals(itemPoJo.getValue(),value)){
                                                     exist = true;
                                                 }
                                             }
                                             if (!exist){
                                                 jsonObject.put("text_1","");
                                             }
                                         }
                                     }
                                 }
                             }
                         }
                        json.put(ContractOutstockEnum.CUSTOMER_PHONE.getAttr(),jsonArray);
                        json.put(ContractOutstockEnum.CUSTOMER_ADDRESS.getAttr(),data.getJSONObject(CustomerManagementEnum.ADDRESS.getAttr()));
                    }
                     if(formId != null){
                         PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByFormId(formId,corpid);
                         if(Objects.nonNull(paasFormExplainEntity) && Objects.equals(paasFormExplainEntity.getDel(), DelEnum.NORMAL.getDel())) {
                             String explains = paasFormExplainEntity.getExplains();
                             if(Objects.nonNull(explains)){
                                 Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMap(explains, null);
                                 if(explainMap!=null){
                                     FieldAttrEntity fieldAttrEntity = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                                     // 判断客户电话子表单是否启用
                                     if(Objects.equals(fieldAttrEntity.getIsOpen(), BasicConstant.ZERO) || Objects.equals(fieldAttrEntity.getVisible(), BasicConstant.ZERO)){
                                         json.put(ContractOutstockEnum.CUSTOMER_PHONE.getAttr(), new JSONArray());
                                     }
                                 }
                             }
                         }
                     }
                     break;
                case WORK_ORDER_OUTSTOCK:
                    param=new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    param.put("corpid",corpid);
                    param.put("id",dataId);
                    param.put("del",0);
                    List<WorkOrderEntity> workOrderEntities = workOrderModel.findEntitys(param);
                    for (WorkOrderEntity entity : workOrderEntities) {
                        JSONObject data = entity.getData();
                        JSONArray customerArray = new JSONArray();
                        JSONArray contactArray = new JSONArray();
                        try {
                            Long customerId = data.getLong(WorkOrderEnum.LINK_CUSTOMER.getAttr());
                            if (Objects.nonNull(customerId)) {
                                JSONObject customerObject = new JSONObject();
                                customerObject.put(StringConstant.SAAS_LINK_BUSINESS_ID,customerId);
                                customerObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME,data.get(WorkOrderEnum.LINK_CUSTOMER_HIDE.getAttr()));
                                customerArray.add(customerObject);
                            }
                        }catch (Exception e){
                            //
                        }
                        try {
                            Long contactId = data.getLong(WorkOrderEnum.LINK_CONTACT.getAttr());
                            if (Objects.nonNull(contactId)) {
                                JSONObject contactObject = new JSONObject();
                                contactObject.put(StringConstant.SAAS_LINK_BUSINESS_ID,contactId);
                                contactObject.put(StringConstant.SAAS_LINK_BUSINESS_NAME,data.get(WorkOrderEnum.LINK_CONTACT_HIDE.getAttr()));
                                contactArray.add(contactObject);
                            }
                        }catch (Exception e){
                          //
                        }
                        json.put(WorkOrderOutstockEnum.LINK_CUSTOMER.getAttr(),customerArray);
                        json.put(WorkOrderOutstockEnum.LINK_CONTACT.getAttr(),contactArray);
                        json.put(WorkOrderOutstockEnum.CUSTOMER_PHONE.getAttr(),data.getJSONArray(WorkOrderEnum.CONTACT_INFORMATION.getAttr()));
                        json.put(WorkOrderOutstockEnum.CUSTOMER_ADDRESS.getAttr(),data.getJSONObject(WorkOrderEnum.ADDRESS.getAttr()));
                    }
                    break;
                default:
                     break;
            }
            businessCustomerListRelyVO.setCustomerObject(json);
        } catch (Exception e) {
            LOG.error("formDataService.businessCusomerListGetRely 出错",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        return businessCustomerListRelyVO;
    }


    /**
     * 未开启JXC,获取退货退款产品,从合同产品表取
     *
     * @return 未退产品
     * @author youli.chen
     * @since 1.0.0
     * 添加时间 2019/4/30
     */
    public List<Long> getRemainProductNotJxc(ProductListDataDTO productListDataDTO) throws XbbException {
        String corpid = productListDataDTO.getCorpid();
        Long contractId = Long.valueOf(productListDataDTO.getRefId());
        // 获取合同产品
        List<ContractProductEntity> contractProductEntityList = contractProductModel.getProductsByConId(contractId, corpid);
        Map<Long, Double> conProductIdAndSum = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for ( ContractProductEntity conPro : contractProductEntityList ) {
            Double productNum = conPro.getProductNum();
            if ( conProductIdAndSum.containsKey(conPro.getProductId()) ) {
                productNum = Arith.add(productNum, conProductIdAndSum.get(conPro.getProductId()));
            }
            conProductIdAndSum.put(conPro.getProductId(), productNum);
        }
        // 根据红冲合同获取已经出库的产品
        Map<Long, Double> productIdAndSum = getRedProduct(corpid, contractId);
        // 判断是否有可以出库的产品
        List<Long> ids = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for ( Map.Entry<Long, Double> conPro : conProductIdAndSum.entrySet() ) {
            Long outKey = conPro.getKey();
            Double outstockProValue = conPro.getValue() == null ? 0D : conPro.getValue();
            Double productValue = productIdAndSum.get(outKey) == null ? 0D : productIdAndSum.get(outKey);
            Double newNum = outstockProValue - productValue;
            if ( newNum > 0D ) {
                ids.add(outKey);
            }
        }
        return ids;
    }

    /**
     * 开启JXC,获取退货退款产品，从出库单表取
     *
     * @return 未退产品
     * @author youli.chen
     * @since 1.0.0
     * 添加时间 2019/4/30
     */
    private List<Long> getRemainProductJxc(ProductListDataDTO productListDataDTO) throws XbbException {
        String corpid = productListDataDTO.getCorpid();
        Long contractId = Long.valueOf(productListDataDTO.getRefId());
        // 获取合同关联出库单
        PaasFormDataEntityExt paasFormDataEntityExt = contractModel.getByKey(contractId, corpid);
        if ( Objects.isNull(paasFormDataEntityExt) ) {
            throw new XbbException(ContractErrorCodeEnum.API_ERROR_203001);
        }
        JSONObject contractData = paasFormDataEntityExt.getData();
        JSONArray outIdArray = contractData.getJSONArray(ContractEnum.OUTSTOCK_ID.getAttr());
        List<Long> outstockIds = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if ( !Objects.isNull(outIdArray) ) {
            outstockIds = outIdArray.toJavaList(Long.class);
        }
        // 获取出库单关联的产品ID
        Map<Long, Double> outstockProduct = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        List<OutstockProductEntity> outstockProductList = outstockProductModel.getProductsByOutstockIdIn(corpid, outstockIds);
        if ( !outstockProductList.isEmpty() ) {
            for ( OutstockProductEntity outstockProductEntity : outstockProductList ) {
                Double productNum = outstockProductEntity.getProductNum();
                if ( outstockProduct.containsKey(outstockProductEntity.getProductId()) ) {
                    productNum = Arith.add(productNum, outstockProduct.get(outstockProductEntity.getProductId()));
                }
                outstockProduct.put(outstockProductEntity.getProductId(), productNum);
            }
        }
        // 根据红冲合同获取已经出库的产品
        Map<Long, Double> productIdAndSum = getRedProduct(corpid, contractId);
        // 判断是否有可以出库的产品
        List<Long> ids = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for ( Map.Entry<Long, Double> outstockPro : outstockProduct.entrySet() ) {
            Long outKey = outstockPro.getKey();
            Double outstockProValue = outstockPro.getValue() == null ? 0D : outstockPro.getValue();
            Double productValue = productIdAndSum.get(outKey) == null ? 0D : productIdAndSum.get(outKey);
            Double newNum = outstockProValue - productValue;
            if ( newNum > 0D ) {
                ids.add(outKey);
            }
        }
        return ids;
    }

    /**
     * 根据红冲合同获取已经出库的产品(根据原合同查询出红冲合同对应的产品，即退货产品)
     *
     * @return 剩余产品
     * @author youli.chen
     * @since 3.22
     */
    @Override
    public Map<Long, Double> getRedProduct(String corpid, Long contractId) throws XbbException {
        // 获取这个合同之前被关联的退货退款
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        List<PaasFormDataEntityExt> paasFormDataEntityExts = paasEsModel.selectByOneCondition(RedundantTemplateTypeEnum.REFUND.getCode(), RefundEnum.CONTRACT_ID.getAttr(), contractId, param, IndexTypeEnum.IDX_SAAS_REFUND);
        List<Long> redContractIds = new ArrayList<>();
        redContractIds.add(-1L);
        for ( PaasFormDataEntityExt paasForm : paasFormDataEntityExts ) {
            JSONObject paasFormData = paasForm.getData();
            Long refundredContractId = FastJsonHelper.getLongOrDefaultFromFormData(paasFormData, RefundEnum.RED_CONTRACT_ID.getAttr(), 0L);
            redContractIds.add(refundredContractId);
        }
        // 获取退货退款单关联的产品ID以及数量
        Map<String, Object> refundMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        refundMap.put("corpid", corpid);
        refundMap.put("contractIdIn", redContractIds);
        refundMap.put("del", DelEnum.NORMAL.getDel());
        List<ContractProductEntity> redContractProductEntityList = contractProductModel.findEntitys(refundMap);
        Map<Long, Double> productIdAndSum = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for ( ContractProductEntity conPro : redContractProductEntityList ) {
            Double productNum = conPro.getProductNum() == null ? 0D : Math.abs(conPro.getProductNum());
            if ( productIdAndSum.containsKey(conPro.getProductId()) ) {
                productNum = Arith.add(productNum, productIdAndSum.get(conPro.getProductId()));
            }
            productIdAndSum.put(conPro.getProductId(), productNum);
        }
        return productIdAndSum;
    }

    private void handleFormEntity(PaasFormEntityExt paasFormEntityExt, Integer saasMark, Integer businessType) {
        if ( Objects.equals(saasMark, SaasMarkEnum.PAAS.getCode()) ) {
            return;
        }
//        if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT.getCode())) {
//            paasFormEntityExt.setName("回款计划");
//        }
        //由于菜单名称可以自定义，因此只过滤默认名称中的“管理”
        String name = paasFormEntityExt.getName();
        name = name.replaceAll("管理", "");
        paasFormEntityExt.setName(name);
    }

    /**
     * 呼叫中心权限判断
     *
     * @param userId
     * @param corpid
     * @param businessType
     * @return
     * @throws XbbException
     */
    private boolean openCall(String userId, String corpid, Integer businessType) throws XbbException {
        boolean isPhoneCall = true;
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
            case CLUE:
            case CONTACT:
            case COMMUNICATE_PLAN:
                isPhoneCall = callCenterCommonService.isOpenCallAndAgent(corpid, userId);
                break;
            default:
                break;
        }
        return isPhoneCall;
    }
    private boolean openAliyunCall(String userId, String corpid, Integer businessType) throws XbbException {
        boolean isPhoneCall = true;
        RedundantTemplateTypeEnum redundantTemplateTypeEnum = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (redundantTemplateTypeEnum) {
            case CUSTOMER:
            case CLUE:
            case CONTACT:
            case COMMUNICATE_PLAN:
                isPhoneCall = callCenterCommonService.isActiveAliyunCall(corpid, userId).IsActiveAliyunAndHasRole();
                break;
            default:
                break;
        }
        return isPhoneCall;
    }

    /**
     * 查询子产品id
     *
     * @param corpid
     * @param categoryId
     * @return
     * @throws
     * @author xingxing.xiao
     * @date 2019/07/04 20:01
     */
    public List<Object> getProductIds(String corpid, Long categoryId) throws XbbException {

        FormDataListDTO dataListDTO = new FormDataListDTO();
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        List<ProductCategoryEntity> productCategoryList = productCategoryService.getSubCategoryIdList(corpid, categoryId);
        if ( Objects.isNull(productCategoryList) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
        List<Long> productCategoryIdIn = new ArrayList<>();
        productCategoryList.forEach(item -> productCategoryIdIn.add(item.getId()));
        if ( !productCategoryIdIn.isEmpty() ) {
            List<Object> categoryIdIn = new ArrayList<>(productCategoryIdIn);
            EsConditionUtil.getConditionList(conditionList, ProductEnum.CATEGORY_ID.getAttr(), "",
                    ProductEnum.CATEGORY_ID.getFieldType(), ConditionEnum.IN.getSymbol(), categoryIdIn);
        }
        // 子产品的 parent_id 不为 0
        conditionList.add(new ConditionsEntityExt(ProductEnum.PARENT_ID.getAttr(), "", ProductEnum.PARENT_ID.getFieldType(), ConditionEnum.NOEQUAL.getSymbol(), Collections.singletonList(0)));
        dataListDTO.setConditions(conditionList);
        dataListDTO.setBusinessType(XbbRefTypeEnum.PRODUCT.getCode());
        dataListDTO.setCorpid(corpid);
        dataListDTO.setDel(0);
        dataListDTO.setSearchSubForm(false);
        // ES 查询
        PaasFormDataEsListVO parentProducts = paasFormDataEsModel.list(dataListDTO, IndexTypeEnum.IDX_SAAS_PRODUCT);
        List<PaasFormDataEntityExt> list = parentProducts.getPaasFormDataESList();
        List<Object> dataIdList = new ArrayList<>();
        for ( PaasFormDataEntityExt entity : list ) {
            dataIdList.add(entity.getId());
        }
        dataIdList.add(-1L);
        return dataIdList;
    }

    /**
     * saas特殊处理
     *
     * @param data
     * @param businessType
     * @param explainMap
     * @throws
     * @author long.rao
     * @date 2019-10-24 15:00
     */
    private void  saasExplainHandle(JSONObject data, Integer businessType, Map<String, FieldAttrEntity> explainMap, String corpid) throws XbbException{
        RedundantTemplateTypeEnum byCode = RedundantTemplateTypeEnum.getByCode(businessType);
        switch (byCode) {
            case CUSTOMER:
                Integer isPublic = getIntegerOrDefaultFromFormData(data, CustomerManagementEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                if (Objects.equals(isPublic, BasicConstant.ONE)) {
                    FieldAttrEntity customerPhone = explainMap.get(CustomerManagementEnum.PHONE.getAttr());
                    if (Objects.nonNull(customerPhone)) {
                        Integer showPublicPool = customerPhone.getShowPublicPool();
                        Integer publicPool = customerPhone.getPublicPool();
                        if (Objects.equals(showPublicPool, BasicConstant.ONE) && Objects.equals(publicPool, BasicConstant.ZERO)) {
                            // 如果客户模板电话字段配置了公海池不可见，那么公海客户的电话不可见
                            customerPhone.setVisible(BasicConstant.ZERO);
                        }
                    }
                }
                break;
            case CLUE:
                Integer publicFlag = getIntegerOrDefaultFromFormData(data, ClueEnum.IS_PUBLIC.getAttr(), BasicConstant.ZERO);
                if (Objects.equals(publicFlag, BasicConstant.ONE)) {
                    FieldAttrEntity cluePhone = explainMap.get(ClueEnum.PHONE.getAttr());
                    if (Objects.nonNull(cluePhone)) {
                        Integer showPublicPool = cluePhone.getShowPublicPool();
                        Integer publicPool = cluePhone.getPublicPool();
                        if (Objects.equals(showPublicPool, BasicConstant.ONE) && Objects.equals(publicPool, BasicConstant.ZERO)) {
                            // 如果模板电话字段配置了公海池不可见，那么公海客户的电话不可见
                            cluePhone.setVisible(BasicConstant.ZERO);
                        }
                    }
                }
                break;
            case SUPPLIER:
                // 补救之前供应商之前的showtype默认为1的情况，最大限度的保留客户数据
                FieldAttrEntity supplierPhone = explainMap.get(SupplierEnum.PHONE.getAttr());
                if(Objects.nonNull(supplierPhone)){
                    SubFormPoJo supplierPhoneSubForm = supplierPhone.getSubForm();
                    if(Objects.nonNull(supplierPhoneSubForm)){
                        List<? extends FieldAttrEntity> items = supplierPhoneSubForm.getItems();
                        if(!items.isEmpty()){
                            for (FieldAttrEntity fieldAttrEntity : items) {
                                if(Objects.nonNull(fieldAttrEntity.getShowType())){
                                    fieldAttrEntity.setShowType(ShowTypeEnum.ALL.getCode());
                                }
                            }
                        }
                    }
                }
                break;
            case SUPPLIER_CONTACT:
                // 补救之前供应商联系人之前的showtype默认为1的情况，最大限度的保留客户数据
                FieldAttrEntity supplierContactPhone = explainMap.get(SupplierContactEnum.PHONE.getAttr());
                if(Objects.nonNull(supplierContactPhone)){
                    SubFormPoJo supplierContactPhoneSubForm = supplierContactPhone.getSubForm();
                    if(Objects.nonNull(supplierContactPhoneSubForm)){
                        List<? extends FieldAttrEntity> items = supplierContactPhoneSubForm.getItems();
                        if(!items.isEmpty()){
                            for (FieldAttrEntity fieldAttrEntity : items) {
                                if(Objects.nonNull(fieldAttrEntity.getShowType())){
                                    fieldAttrEntity.setShowType(ShowTypeEnum.ALL.getCode());
                                }
                            }
                        }
                    }
                }
                break;
                //TODO 这段没用了 本来传进来就是回款单
           /* case PAYMENT_SHEET:
                PaasFormExplainEntity paymentExplain = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), corpid);
                if (Objects.nonNull(paymentExplain)) {
                    //预收款核销和坏账没有支付方式
                    String paymentSheetType = data.getString(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr());
                    if(Objects.equals(paymentSheetType,PaymentSheetTypeEnum.WRITE_OFF_PREPAYMENT.getCode()) || Objects.equals(paymentSheetType,PaymentSheetTypeEnum.BAD_PAYMENT.getCode())){
                        break;
                    }
                    explainMap.get(PaymentSheetEnum.PAY_METHOD.getAttr()).setItems(ExplainUtil.getExplainMap(
                            paymentExplain.getExplains(), PaymentSheetEnum.PAY_METHOD.getAttr()).get(PaymentSheetEnum.PAY_METHOD.getAttr()).getItems());
                }
                break;*/
            default:
                break;
        }
    }

    /**
     * 设置特殊参数
     *
     * @param formDataSaveDTO
     * @param validateDataDTO
     * @throws
     * @author long.rao
     * @date 2019-10-09 10:36
     */
    private void setSpecialParam(FormDataAddDTO formDataSaveDTO, ValidateDataDTO validateDataDTO) throws XbbException {
        if ( Objects.equals(formDataSaveDTO.getBusinessType(), XbbRefTypeEnum.QUOTATION.getCode()) ) {
            // 报价单组号不为1.0时，代表创建新版本(目前用于报价单新版本时不用校验同一组号的报价名称)
            JSONObject data = formDataSaveDTO.getDataList();
            String version = FastJsonHelper.getStringOrDefaultFromFormData(data, QuotationEnum.VERSION.getAttr(), StringConstant.DEFAULT_VERSION);
            if ( !Objects.equals(version, StringConstant.DEFAULT_VERSION) ) {
                validateDataDTO.setNewVersion(BasicConstant.ONE);
            }
        } else if (Objects.equals(formDataSaveDTO.getBusinessType(), XbbRefTypeEnum.PRODUCT.getCode())) {
            JSONObject data = formDataSaveDTO.getDataList();
            JSONObject specObj = data.getJSONObject(ProductEnum.SPECIFICATION.getAttr());
            if (Objects.isNull(specObj) || (Objects.equals(specObj.getInteger(ProductConstant.ADVANCED_MODE), 0) && StringUtil.isEmpty(specObj.getString(ProductConstant.SINGLE_SPEC)))) {
                if (Objects.equals(data.getInteger(ProductEnum.IS_NOTIFY.getAttr()), 1)) {
                    List<StockNotifyPojo> stockNotifyList = data.getJSONArray(ProductEnum.STOCK_NOTIFY.getAttr()).toJavaList(StockNotifyPojo.class);
                    for (StockNotifyPojo stockNotifyPojo : stockNotifyList) {
                        // 没有规格值得时候用空字符串
                        if (Objects.isNull(stockNotifyPojo.getArray_1())) {
                            JSONArray jsonArray = new JSONArray();
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("", "");
                            jsonArray.add(jsonObject);
                            stockNotifyPojo.setArray_1(jsonArray);
                        }
                    }
                    data.put(ProductEnum.STOCK_NOTIFY.getAttr(), JSON.parseArray(JSON.toJSONString(stockNotifyList)));
                }
            }
        }
    }

    /**
     * 校验应用和菜单是否开启
     *
     * @param appId
     * @param menuId
     * @param corpid
     * @return paasMenuEntity
     * @throws XbbException
     * @update 2020/5/25 by zcp 增加返回值
     */
    private PaasMenuEntity validateAppAndMenu(Long appId, Long menuId, String corpid) throws XbbException {
        Boolean appEnable = paasAppService.validateAppEnable(appId, "", null, corpid);
        if ( !appEnable ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.APP_NOT_ENABLE);
        }
        PaasMenuEntity paasMenuEntity = paasMenuModel.getByKey(menuId, corpid);
        if ( Objects.nonNull(paasMenuEntity) && Objects.equals(0, paasMenuEntity.getEnable()) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_ENABLE);
        }
        return paasMenuEntity;
    }
    /**
     * 校验应用和菜单是否开启，校验菜单时同时校验其父级菜单是否开启
     * @param appId
     * @param menuId
     * @param corpid
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void validateAppAndMenuParentMenu(Long appId, Long menuId, String corpid) throws XbbException {
        PaasMenuEntity paasMenuEntity = validateAppAndMenu(appId, menuId, corpid);
        //除了判断该菜单本身是否开启外，再判断其父级菜单是否开启
        if (Objects.nonNull(paasMenuEntity) && !Objects.equals(paasMenuEntity.getParentId(), BasicConstant.ZERO_LONG)) {
            PaasMenuEntity parentMenuEntity = paasMenuModel.getByKey(paasMenuEntity.getParentId(), corpid);
            if ( Objects.nonNull(parentMenuEntity) && Objects.equals(0, parentMenuEntity.getEnable()) ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.MENU_NOT_ENABLE);
            }
        }
    }

    /**
     * 处理回款单的回款金额的特殊汇总
     *
     * @param explainMap         解释
     * @param formDataSummaryDTO 入参
     * @param numCountList       结果列表
     * @param formDataSummaryVO  回参
     * @throws XbbException 异常
     * @author 徐俊杰
     * @date 2019/11/25 16:42
     * @since v1.0
     */
    private void sheetSummary(Map<String, FieldAttrEntity> explainMap, FormDataSummaryDTO formDataSummaryDTO, List<AggSumVO> numCountList, FormDataSummaryVO formDataSummaryVO, XbbRefTypeEnum type) throws XbbException {
        List<FieldAttrEntity> sheetAttrList = new ArrayList<>();
        if (Objects.equals(type, XbbRefTypeEnum.PAYMENT_SHEET) && explainMap.containsKey(PaymentSheetEnum.AMOUNT.getAttr())) {
            sheetAttrList.add(explainMap.get(PaymentSheetEnum.AMOUNT.getAttr()));
        } else if (Objects.equals(type, XbbRefTypeEnum.PAY_SHEET) && explainMap.containsKey(PaySheetEnum.AMOUNT.getAttr())) {
            sheetAttrList.add(explainMap.get(PaySheetEnum.AMOUNT.getAttr()));
        }
        List<ConditionsEntityExt> conditionsEntityExts = formDataSummaryDTO.getConditions();
        removeDataPoint(conditionsEntityExts);
        //非坏账
        List<Object> notBadCodeList = null;
        ConditionsEntityExt typeConditionNotBad = null;
        if (Objects.equals(type, XbbRefTypeEnum.PAYMENT_SHEET)) {
            notBadCodeList = new ArrayList<>(PaymentSheetTypeEnum.getNotBadCodeList());
            typeConditionNotBad = new ConditionsEntityExt(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), null, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getFieldType(), ConditionEnum.IN.getSymbol(), notBadCodeList);
        } else if (Objects.equals(type, XbbRefTypeEnum.PAY_SHEET)) {
            notBadCodeList = new ArrayList<>(PaySheetTypeEnum.getNotBadCodeList());
            typeConditionNotBad = new ConditionsEntityExt(PaySheetEnum.PAY_SHEET_TYPE.getAttr(), null, PaySheetEnum.PAY_SHEET_TYPE.getFieldType(), ConditionEnum.IN.getSymbol(), notBadCodeList);
        }
        conditionsEntityExts.add(typeConditionNotBad);
        List<AggSumVO> amountCountListNotBad = getNumCount(sheetAttrList, formDataSummaryDTO);
        //坏账
        conditionsEntityExts.remove(conditionsEntityExts.size() - 1);
        removeDataPoint(conditionsEntityExts);
        List<Object> badCodeList = null;
        ConditionsEntityExt typeConditionBad = null;
        if (Objects.equals(type, XbbRefTypeEnum.PAYMENT_SHEET)) {
            badCodeList = Collections.singletonList(PaymentSheetTypeEnum.BAD_PAYMENT.getCode());
            typeConditionBad = new ConditionsEntityExt(PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), null, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getFieldType(), ConditionEnum.EQUAL.getSymbol(), badCodeList);
        } else if (Objects.equals(type, XbbRefTypeEnum.PAY_SHEET)) {
            badCodeList = Collections.singletonList(PaySheetTypeEnum.BAD_PAY.getCode());
            typeConditionBad = new ConditionsEntityExt(PaySheetEnum.PAY_SHEET_TYPE.getAttr(), null, PaySheetEnum.PAY_SHEET_TYPE.getFieldType(), ConditionEnum.EQUAL.getSymbol(), badCodeList);
        }
        conditionsEntityExts.add(typeConditionBad);
        List<AggSumVO> amountCountListBad = getNumCount(sheetAttrList, formDataSummaryDTO);
        JSONObject jsonObject = new JSONObject();
        //包装参数
        for ( AggSumVO aggSumVO : numCountList ) {
            jsonObject.put(aggSumVO.getAttr(), aggSumVO.getValue());
            if ( Objects.equals(aggSumVO.getAttr(), PaymentSheetEnum.AMOUNT.getAttr()) || Objects.equals(aggSumVO.getAttr(), PaySheetEnum.AMOUNT.getAttr())) {
                //根据精确度获取0
                FieldAttrEntity amountFieldAttr = null;
                String paymentAmountStr = null;
                if (Objects.equals(type, XbbRefTypeEnum.PAYMENT_SHEET)) {
                    amountFieldAttr = explainMap.get(PaymentSheetEnum.AMOUNT.getAttr());
                    paymentAmountStr = I18nMessageUtil.getMessage(I18nStringConstant.PAYMENT);
                } else if (Objects.equals(type, XbbRefTypeEnum.PAY_SHEET)) {
                    amountFieldAttr = explainMap.get(PaySheetEnum.AMOUNT.getAttr());
                    paymentAmountStr = I18nMessageUtil.getMessage(I18nStringConstant.PAY);
                }
                Integer accuracy = (amountFieldAttr == null) ? null : amountFieldAttr.getAccuracy();
                Object zeroAccuracy = AttrDecimalPrecisionHelper.parseThousandth(0, accuracy);
                if ( CollectionsUtil.isNotEmpty(amountCountListNotBad) ) {
                    paymentAmountStr += amountCountListNotBad.get(0).getValue();
                } else {
                    paymentAmountStr += String.valueOf(zeroAccuracy);
                }
                paymentAmountStr += "，" + I18nMessageUtil.getMessage(I18nStringConstant.BAD_DEBT);
                if ( CollectionsUtil.isNotEmpty(amountCountListBad) ) {
                    paymentAmountStr += amountCountListBad.get(0).getValue();
                } else {
                    paymentAmountStr += String.valueOf(zeroAccuracy);
                }
                jsonObject.put(aggSumVO.getAttr(), paymentAmountStr);
            }
        }
        formDataSummaryVO.setSummary(jsonObject);
    }

    /**
     * 移除data.，因为再次调用getNumCount时会加入
     *
     * @param conditionsEntityExts 条件集合
     * @author 徐俊杰
     * @date 2019/11/26 15:08
     * @since v1.0
     */
    private void removeDataPoint(List<ConditionsEntityExt> conditionsEntityExts) {
        for ( ConditionsEntityExt conditionsEntityExt : conditionsEntityExts ) {
            String attr = conditionsEntityExt.getAttr();
            if ( attr.contains("data.") ) {
                attr = attr.replace("data.", "");
                conditionsEntityExt.setAttr(attr);
            }
        }
    }

    /**
     * 编辑or详情页得到明细
     *
     * @param sheetTypeEnum         回/付款单类型
     * @param parseSingleRowDataDTO 解析单行数据dto
     * @param corpid                公司id
     * @param formDataId            数据id
     * @param formDataEntityExt     数据实体
     * @return com.alibaba.fastjson.JSONArray
     * @throws XbbException
     * @author zcp
     * @date 19/11/28 028 15:45
     * @update 19/11/28 028 15:45
     * @version v1.0
     * @since v1.0
     */
    private JSONArray getAmountDetail4exist(SheetTypeEnum sheetTypeEnum, ParseSingleRowDataDTO parseSingleRowDataDTO, String corpid, Long formDataId, PaasFormDataEntityExt formDataEntityExt) throws XbbException {
        boolean payFlag = SheetTypeEnum.validatePay(sheetTypeEnum);
        if (!payFlag) {
            //非回/付款单则无明细
            return null;
        }
        JSONArray amountDetail = new JSONArray();
        XbbRefTypeEnum xbbRefTypeEnum = sheetTypeEnum.getXbbRefTypeEnum();
        if ( Objects.equals(formDataEntityExt.getAlone(), SheetAloneEnum.NORMAL.getCode()) ) {
            //没有父子回款，只有一个父，则默认把本身作为子明细
            JSONObject detailData = formDataEntityExt.getData();
            Double amount = FundHelp.getSheetAmountBySheetType(sheetTypeEnum, detailData);
            amountDetail = fundHelp.getDefaultAmountDetail(detailData, amount);
        } else {
            //因为前端明细内恒展示几个固定字段，而预收/付款核销、红冲预收款核销(退到余额)的amount是为null的，为了方便展示，把核销金额置入回款金额amount内（目前编辑时不编辑明细，而且就算编辑，在保存时会把预收款核销类型回款单的amount给remove掉）
            boolean writeOffPrepaymentFlag = SheetTypeEnum.onlyWriteOffAmount(sheetTypeEnum.getCode());
            String attrAmount = PaymentSheetEnum.AMOUNT.getAttr();
            String attrWriteOff = PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr();
            IndexTypeEnum indexTypeEnum = IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET;
            boolean paySheetFlag = false;
            if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_SHEET)) {
                attrAmount = PaySheetEnum.AMOUNT.getAttr();
                attrWriteOff = PaySheetEnum.WRITE_OFF_AMOUNT.getAttr();
                indexTypeEnum = IndexTypeEnum.IDX_SAAS_PAYPLAN_SHEET;
                paySheetFlag = true;
            }
            List<PaasFormDataEntityExt> childEsDataList = fundHelp.getChildEsDataListByParentUuid(indexTypeEnum, corpid, formDataEntityExt.getUuid(),"addTime");
            // 解析数据信息
            for ( PaasFormDataEntityExt entityExt : childEsDataList ) {
                JSONObject detailData = entityExt.getData();
                if ( detailData != null ) {
                    //处理签订人等
                    parseSingleRowDataDTO.setDataJsonObject(detailData);
                    ParseSingleRowDataVO parseSingleRowDataVO = formDataUpdateGetAnalysisDataHelp.parseSingleRowData(parseSingleRowDataDTO);
                    detailData = parseSingleRowDataVO.getResult();
                    //处理关联客户等
                    SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
                    saasAnalysisDataDTO.setCorpid(parseSingleRowDataDTO.getCorpid());
                    if (paySheetFlag) {
                        payPlanSheetModel.formatData(saasAnalysisDataDTO, detailData);
                    } else {
                        paymentSheetModel.formatData(saasAnalysisDataDTO, detailData);
                    }
                    detailData.put(StringConstant.DATA_ID, entityExt.getId());
                    if ( writeOffPrepaymentFlag ) {
                        //预收款核销，则把核销金额置入回款金额amount内，因为前端明细内恒展示几个固定字段，
                        detailData.put(attrAmount, detailData.getDoubleValue(attrWriteOff));
                    }
                    amountDetail.add(detailData);
                }
            }
        }
        return amountDetail;
    }

    /**
     * 查询客户或线索名称和电话判重设置
     *
     * @param corpid
     * @param formId
     * @param explainList 解释字段
     * @param businessType 业务类型
     * @author xingxing.xiao
     * @date 2019/11/12 20:08
     */
    @Override
    public void handlerCustomerRepeat(String corpid, Long formId, List<FieldAttrEntity> explainList, Integer businessType) {
       phoneHelp.handlerCustomerRepeat(corpid, formId, explainList, businessType);
    }


    @Override
    public DistributorAddressVo getDistributorAddress(DistributorAddressDTO distributorAddressDTO) throws XbbException {
        DistributorAddressVo distributorAddressVo = new DistributorAddressVo();
        Integer businessType = distributorAddressDTO.getSourceBusinessType();
        String corpid = distributorAddressDTO.getCorpid();
        Long dataId = distributorAddressDTO.getDistributorId();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("dataId", dataId);
        param.put("del", DelEnum.NORMAL.getDel());
        List<CustomerSubDataEntity> entitys = customerSubDataModel.findEntitys(param);
        //收货地址集合
        List<ContractSubDataExt> shippingAddress = new ArrayList<>();
        if (Objects.nonNull(entitys)){
            for (PaasFormSubDataEntity entity : entitys) {
                if (Objects.equals(DistributorEnum.SHIPPING_ADDRESS.getAttr(), entity.getAttr())){
                    ContractSubDataExt contractSubDataExt = new ContractSubDataExt();
                    contractSubDataExt.setData(entity.getData());
                    contractSubDataExt.setFormId(entity.getFormId());
                    distributorAddressDTO.setFormId(entity.getFormId());
                    contractSubDataExt.setDataId(entity.getId());
                    shippingAddress.add(contractSubDataExt);
                }
            }
            distributorAddressVo.setPaasFormDataESList(shippingAddress);
            Integer page = distributorAddressDTO.getPage();
            Integer pageSize = distributorAddressDTO.getPageSize();
            PageHelper pageHelper = PageHelperUtil.initPageHelper(entitys.size(), page, pageSize, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
            distributorAddressVo.setPageHelper(pageHelper);
        }
        List<FieldAttrEntity> headList = new ArrayList<>();
        //拿经销商档案的收货地址解释
        PaasFormExplainEntity explainEntity = paasFormExplainModel.getByBusinessType4Distributor(XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode());
        List<FieldAttrEntity> fieldAttrEntityList = (List<FieldAttrEntity>)JSONArray.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
        for (FieldAttrEntity fieldAttrEntity : fieldAttrEntityList) {
            if (Objects.equals(DistributorEnum.SHIPPING_ADDRESS.getAttr(), fieldAttrEntity.getAttr())){
                List<? extends FieldAttrEntity> items = fieldAttrEntity.getSubForm().getItems();
                for (FieldAttrEntity item : items) {
                    headList.add(item);
                }
            }
        }
        distributorAddressVo.setHeadList(headList);
        PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();

        // 查询数据库菜单名称,出库发货单是多模板，没有单独的菜单
        // if (Objects.equals(businessType,XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())){
        //     PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType4Distributor(businessType,corpid,DistributorMarkEnum.DISTRIBUTOR.getCode(),null);
        //     paasFormEntityExt.setBusinessName(paasFormEntity.getName());
        // } else {
        //     PaasMenuEntity paasMenuEntity = paasMenuModel.getByAlias4Distributor(XbbRefTypeEnum.getByCode(businessType).getAlias(), corpid, DistributorMarkEnum.DISTRIBUTOR.getCode());
        //     paasFormEntityExt.setBusinessName(paasMenuEntity.getName());
        // }

        // 不取菜单名称，先写死
        paasFormEntityExt.setBusinessName("选择收货人");
        //前端渲染需要
        paasFormEntityExt.setMainAttr("text_1");
        paasFormEntityExt.setId(explainEntity.getFormId());
        distributorAddressVo.setForm(paasFormEntityExt);
        distributorAddressVo.setTopPermissions(new ArrayList<>());
        distributorAddressVo.setEnableSearch(BasicConstant.ZERO);
        return distributorAddressVo;
    }

    @Override
    public DistributorReceiverVo getDistributorReceiver(DistributorReceiverDTO distributorReceiverDTO) throws XbbException {
        DistributorReceiverVo distributorReceiverVo = new DistributorReceiverVo();
        Integer businessType = distributorReceiverDTO.getSourceBusinessType();
        String corpid = distributorReceiverDTO.getCorpid();
        Long warehouseId = distributorReceiverDTO.getWarehouseId();
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("corpid", corpid);
        param.put("dataId", warehouseId);
        param.put("del", DelEnum.NORMAL.getDel());
        List<WarehouseSubDataEntity> entitys = warehouseSubDataModel.findEntitys(param);
        // 寄件人明细
        List<WarehouseSubDataEntity> receiverAddress = new ArrayList<>();
        if (Objects.nonNull(entitys)){
            for (PaasFormSubDataEntity entity : entitys) {
                if (Objects.equals(WarehouseEnum.SENDER_DETAILS.getAttr(), entity.getAttr())){
                    distributorReceiverDTO.setFormId(entity.getFormId());
                    WarehouseSubDataEntity warehouseSubDataEntity = new WarehouseSubDataEntity();
                    warehouseSubDataEntity.setData(entity.getData());
                    warehouseSubDataEntity.setFormId(entity.getFormId());
                    warehouseSubDataEntity.setDataId(entity.getId());
                    receiverAddress.add(warehouseSubDataEntity);
                }
            }
            distributorReceiverVo.setPaasFormDataESList(receiverAddress);
            // 分页
            Integer page = distributorReceiverDTO.getPage();
            Integer pageSize = distributorReceiverDTO.getPageSize();
            PageHelper pageHelper = PageHelperUtil.initPageHelper(entitys.size(), page, pageSize, PageConstant.DEFAULT_PAGE_SIZE_SMALL);
            distributorReceiverVo.setPageHelper(pageHelper);
        }
        //拿仓库寄件方解释
        List<FieldAttrEntity> headList = new ArrayList<>();
        PaasFormExplainEntity explainEntity = paasFormExplainModel.getByBusinessType(XbbRefTypeEnum.WAREHOUSE.getCode(), corpid);
        List<FieldAttrEntity> fieldAttrEntityList = (List<FieldAttrEntity>)JSONArray.parseArray(explainEntity.getExplains(), FieldAttrEntity.class);
        entityFor: for (FieldAttrEntity fieldAttrEntity : fieldAttrEntityList) {
            if (Objects.equals(WarehouseEnum.SENDER_DETAILS.getAttr(), fieldAttrEntity.getAttr())){
                List<? extends FieldAttrEntity> items = fieldAttrEntity.getSubForm().getItems();
                // 只拿系统定义的3个字段，类型需要改名为寄件人
                for (FieldAttrEntity item : items) {
                    if (Objects.equals(item.getAttr(), "text_1")) {
                        item.setAttrName("寄件人");
                        headList.add(item);
                    } else if (Objects.equals(item.getAttr(), "text_2") || Objects.equals(item.getAttr(), "address_1")) {
                        headList.add(item);
                    }
                    if (headList.size() == 3) {
                        break entityFor;
                    }
                }
            }
        }
        distributorReceiverVo.setHeadList(headList);

        PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();

        // 查询数据库菜单名称,出库发货单是多模板，没有单独的菜单
        // if (Objects.equals(businessType,XbbRefTypeEnum.CONTRACT_OUTSTOCK.getCode())){
        //     PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType4Distributor(businessType,corpid,DistributorMarkEnum.DISTRIBUTOR.getCode(),null);
        //     paasFormEntityExt.setBusinessName(paasFormEntity.getName());
        // }

        // 不取菜单名称，先写死
        paasFormEntityExt.setBusinessName("选择寄件人");
        //前端渲染需要
        paasFormEntityExt.setMainAttr(CommonBusinessFieldUtil.getFormEntityMainAttr(businessType));
        paasFormEntityExt.setId(explainEntity.getFormId());
        distributorReceiverVo.setForm(paasFormEntityExt);
        distributorReceiverVo.setTopPermissions(new ArrayList<>());
        distributorReceiverVo.setEnableSearch(BasicConstant.ZERO);
        return distributorReceiverVo;
    }

    /**
     * 回/付款单负值转换为正值
     *
     * @param xbbRefTypeEnum 业务类型
     * @param detailData data数据
     * @author 徐俊杰
     * @date 2019/12/6 22:13
     * @since v1.0
     */
    private void paymentSheetAmountTransform(XbbRefTypeEnum xbbRefTypeEnum, JSONObject detailData) {
        String attrAmount;
        String attrWriteOff;
        String amountTime = "";
        if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAY_SHEET)) {
            attrAmount = PaySheetEnum.AMOUNT.getAttr();
            attrWriteOff = PaySheetEnum.WRITE_OFF_AMOUNT.getAttr();
            amountTime = PaySheetEnum.REAL_PAY_TIME.getAttr();
            transform(detailData, attrAmount);
            transform(detailData, attrWriteOff);
        } else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.PAYMENT_SHEET)) {
            attrAmount = PaymentSheetEnum.AMOUNT.getAttr();
            attrWriteOff = PaymentSheetEnum.WRITE_OFF_AMOUNT.getAttr();
            amountTime = PaymentSheetEnum.PAYMENT_TIME.getAttr();
            transform(detailData, attrAmount);
            transform(detailData, attrWriteOff);
        } else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.OTHER_INCOME)) {
            attrAmount = OtherIncomeEnum.AMOUNT.getAttr();
            amountTime = OtherIncomeEnum.INCOME_TIME.getAttr();
            transform(detailData, attrAmount);
        } else if (Objects.equals(xbbRefTypeEnum, XbbRefTypeEnum.OTHER_EXPENSE)) {
            attrAmount = OtherExpenseEnum.AMOUNT.getAttr();
            amountTime = OtherExpenseEnum.EXPENSE_TIME.getAttr();
            transform(detailData, attrAmount);
        }
        if (Objects.nonNull(amountTime)) {
            detailData.put(amountTime, DateUtil.getNow());
        }
    }

    /**
     * 负值转换为正值
     *
     * @param detailData data数据
     * @param amountAttr 需要转换的字段
     * @author 徐俊杰
     * @date 2019/12/6 22:19
     * @since v1.0
     */
    private void transform(JSONObject detailData, String amountAttr) {
        double amount = detailData.getDoubleValue(amountAttr);
        amount = amount < BasicConstant.ZERO ? -amount : amount;
        detailData.put(amountAttr, amount);
    }


    /**
     * 编辑退货退款或采购退货单中处理关联发票/回款单/应收款/付款单格式
     * @param data 数据
     * @param corpid 公司ID
     * @param formDataUpdateGetDTO 入参
     * @param businessType 业务类型code
     * @throws XbbException error
     * @author zhouwq
     * @date 2019/12/17 18:29
     */
    private void formatInvoiceAndSheetInRefund(JSONObject data, String corpid, FormDataUpdateGetDTO formDataUpdateGetDTO, Integer businessType) throws XbbException {
        JSONArray invoiceArray;
        JSONArray sheetArray;
        //资金3.0目前只对crm部分增加了应收款，进销存还未有该功能
        JSONArray paymentArray = new JSONArray();
        if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
            invoiceArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, RefundEnum.INVOICES.getAttr(), new JSONArray());
            sheetArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, RefundEnum.PAYMENT_SHEETS.getAttr(), new JSONArray());
            paymentArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, RefundEnum.PAYMENTS.getAttr(), new JSONArray());
        } else {
            invoiceArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ReturnedPurchaseEnum.INVOICES.getAttr(), new JSONArray());
            sheetArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(data, ReturnedPurchaseEnum.PAY_SHEETS.getAttr(), new JSONArray());
        }
        Integer distributorMark = formDataUpdateGetDTO.getDistributorMark();
        if (invoiceArray.size() > 0) {
            List<Long> invoiceIds = new ArrayList<>();
            for (Object obj : invoiceArray) {
                JSONObject invoiceObj = (JSONObject) obj;
                invoiceIds.add(invoiceObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
            }
            if (invoiceIds.size() > 0) {
                PaasFormEntity paasFormEntity;
                if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                    paasFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.INVOICE.getCode(), corpid, distributorMark, null);
                } else {
                    paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PURCHASE_INVOICE.getCode(), corpid);
                }
                ButtonGetDTO buttonGetDTO = new ButtonGetDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, buttonGetDTO);
                BeanUtil.copyProperties(paasFormEntity, buttonGetDTO);
                buttonGetDTO.setDataIdIn(invoiceIds);
                try{
                    ButtonGetVO buttonGetVO = buttonGet(buttonGetDTO);
                    if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                        data.put(RefundEnum.INVOICES.getAttr(), buttonGetVO.getDataList());
                    } else {
                        data.put(ReturnedPurchaseEnum.INVOICES.getAttr(), buttonGetVO.getDataList());
                    }
                } catch (Exception e){
                    if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                        data.put(RefundEnum.INVOICES.getAttr(), new ArrayList<>());
                    } else {
                        data.put(ReturnedPurchaseEnum.INVOICES.getAttr(), new ArrayList<>());
                    }
                    LOG.error("关联发票已删除", e);
                }
            }
        }

        if (sheetArray.size() > 0) {
            List<Long> paymentSheetIds = new ArrayList<>();
            for (Object obj : sheetArray) {
                JSONObject paymentObj = (JSONObject) obj;
                paymentSheetIds.add(paymentObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
            }
            if (paymentSheetIds.size() > 0) {
                PaasFormEntity paasFormEntity;
                ButtonGetDTO buttonGetDTO = new ButtonGetDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, buttonGetDTO);
                int redBusinessType;
                if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                    paasFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), corpid, distributorMark, null);
                    redBusinessType = XbbRefTypeEnum.RED_PAYMENT_SHEET.getCode();
                } else {
                    paasFormEntity = paasFormModel.getByBusinessType(XbbRefTypeEnum.PAY_SHEET.getCode(), corpid);
                    redBusinessType = XbbRefTypeEnum.RED_WRITE_OFF_PAY.getCode();
                }
                BeanUtil.copyProperties(paasFormEntity, buttonGetDTO);
                buttonGetDTO.setBusinessType(redBusinessType);
                buttonGetDTO.setDataIdIn(paymentSheetIds);
                try {
                    ButtonGetVO buttonGetVO = buttonGet(buttonGetDTO);
                    if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                        data.put(RefundEnum.PAYMENT_SHEETS.getAttr(), buttonGetVO.getDataList());
                    } else {
                        data.put(ReturnedPurchaseEnum.PAY_SHEETS.getAttr(), buttonGetVO.getDataList());
                    }
                } catch (Exception e) {
                    if (Objects.equals(businessType, XbbRefTypeEnum.REFUND.getCode())) {
                        data.put(RefundEnum.PAYMENT_SHEETS.getAttr(), new ArrayList<>());
                    } else {
                        data.put(ReturnedPurchaseEnum.PAY_SHEETS.getAttr(), new ArrayList<>());
                    }
                    LOG.error("关联回/付款单已删除", e);
                }
            }
        }

        if (paymentArray.size() > 0) {
            List<Long> paymentIds = new ArrayList<>();
            for (Object obj : paymentArray) {
                JSONObject paymentObj = (JSONObject) obj;
                paymentIds.add(paymentObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
            }
            if (paymentIds.size() > 0) {
                ButtonGetDTO buttonGetDTO = new ButtonGetDTO();
                BeanUtil.copyProperties(formDataUpdateGetDTO, buttonGetDTO);
                int redBusinessType = XbbRefTypeEnum.PAYMENT.getCode();
                PaasFormEntity paasFormEntity = paasFormModel.getByBusinessType4Distributor(XbbRefTypeEnum.PAYMENT.getCode(), corpid, distributorMark, null);
                BeanUtil.copyProperties(paasFormEntity, buttonGetDTO);
                buttonGetDTO.setBusinessType(redBusinessType);
                buttonGetDTO.setDataIdIn(paymentIds);
                try {
                    ButtonGetVO buttonGetVO = buttonGet(buttonGetDTO);
                    data.put(RefundEnum.PAYMENTS.getAttr(), buttonGetVO.getDataList());
                } catch (Exception e) {
                    data.put(RefundEnum.PAYMENTS.getAttr(), new ArrayList<>());
                    LOG.error("关联应收款已删除", e);
                }
            }
        }
    }

    /**
     * 删除不可红冲回款单
     * @param corpid 公司ID
     * @param paymentSheetIdIn 回款单ID集合
     * @param paasFormDataESList 回款单列表
     * @throws XbbException error
     * @author zhouwq
     * @date 2019/12/18 13:58
     */
    private void removeRedPaymentSheetByRedAmount(String corpid, List<Long> paymentSheetIdIn, List<PaasFormDataEntityExt> paasFormDataESList) throws XbbException {
        Map<Long, Double> paymentSheetIdInToRedAmount = paymentSheetService.sumRedAmountByPaymentSheetIdIn(corpid, paymentSheetIdIn);
        Iterator<PaasFormDataEntityExt> iterator = paasFormDataESList.iterator();
        while (iterator.hasNext()) {
            PaasFormDataEntityExt paasFormDataEntityExt = iterator.next();
            JSONObject data = paasFormDataEntityExt.getData();
            Long dataId = paasFormDataEntityExt.getDataId();
            String type = FastJsonHelper.getStringOrDefaultFromFormData(data, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), "");
            Double amount = FundHelp.getSheetAmount4PaymentSheet(data, type);
            Double redAmount = paymentSheetIdInToRedAmount.get(dataId);
            if (redAmount != null) {
                if ((amount + redAmount) <= 0) {
                    iterator.remove();
                }
            }
        }
    }

    /**
     * 删除不可红冲付款单
     * @param corpid 公司ID
     * @param paySheetIdIn 付款单ID集合
     * @param paasFormDataESList 付款单列表
     * @throws XbbException error
     * @author zhouwq
     * @date 2020/3/6 15:11
     */
    private void removeRedPaySheetByRedAmount(String corpid, List<Long> paySheetIdIn, List<PaasFormDataEntityExt> paasFormDataESList) throws XbbException {
        Map<Long, Double> paymentSheetIdInToRedAmount = payPlanSheetService.sumRedAmountByPaySheetIdIn(corpid, paySheetIdIn);
        Iterator<PaasFormDataEntityExt> iterator = paasFormDataESList.iterator();
        while (iterator.hasNext()) {
            PaasFormDataEntityExt paasFormDataEntityExt = iterator.next();
            JSONObject data = paasFormDataEntityExt.getData();
            Long dataId = paasFormDataEntityExt.getDataId();
            String type = FastJsonHelper.getStringOrDefaultFromFormData(data, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), "");
            Double amount;
            if (Objects.equals(type, PaySheetTypeEnum.WRITE_OFF_PREPAY.getCode())) {
                amount = getDoubleOrDefaultFromFormData(data, PaySheetEnum.WRITE_OFF_AMOUNT.getAttr(), 0D);
            } else {
                amount = getDoubleOrDefaultFromFormData(data, PaySheetEnum.AMOUNT.getAttr(), 0D);
            }
            Double redAmount = paymentSheetIdInToRedAmount.get(dataId);
            if (redAmount != null) {
                if ((amount + redAmount) <= 0) {
                    iterator.remove();
                }
            }
        }
    }

    private void removeRefObject(Integer businessType,List<PaasFormDataEntityExt> paasFormDataESList, Map<Long,Double> refIdMap) throws XbbException{
        Iterator<PaasFormDataEntityExt> iterator = paasFormDataESList.iterator();
        while (iterator.hasNext()) {
            PaasFormDataEntityExt paasFormDataEntityExt = iterator.next();
            Long id = paasFormDataEntityExt.getId();
            JSONObject data = paasFormDataEntityExt.getData();
            JSONObject sourceData = paasFormDataEntityExt.getSourceData();
            if(Objects.isNull(sourceData)){
                paasFormDataEntityExt.setSourceData(data);
                sourceData = paasFormDataEntityExt.getSourceData();
            }
            Double amount = 0D;
            Double invoiceAmount = 0D;
            if(Objects.equals(businessType,XbbRefTypeEnum.CONTRACT.getCode())){
                amount = getDoubleOrDefaultFromFormData(data,ContractEnum.AMOUNT.getAttr(),0D);
                invoiceAmount = getDoubleOrDefaultFromFormData(data,ContractEnum.INVOICE_AMOUNT.getAttr(),0D);
            }else if(Objects.equals(businessType,XbbRefTypeEnum.PAYMENT.getCode())){
                amount = getDoubleOrDefaultFromFormData(data,PaymentEnum.AMOUNT.getAttr(),0D);
                invoiceAmount = getDoubleOrDefaultFromFormData(data,PaymentEnum.INVOICE_AMOUNT.getAttr(),0D);
            }else if(Objects.equals(businessType, XbbRefTypeEnum.PAYMENT_SHEET.getCode())){
                amount = getDoubleOrDefaultFromFormData(data,PaymentSheetEnum.AMOUNT.getAttr(),0D);
                invoiceAmount = getDoubleOrDefaultFromFormData(data,PaymentSheetEnum.INVOICE_AMOUNT.getAttr(),0D);
            }
            if(!Objects.equals(businessType,XbbRefTypeEnum.CUSTOMER_MANAGEMENT.getCode())) {
                if (amount - invoiceAmount <= 0) {
                    if (Objects.nonNull(refIdMap)) {
                        if (!refIdMap.containsKey(id)) {
                            iterator.remove();
                        } else {
                            if(Objects.equals(businessType, XbbRefTypeEnum.CONTRACT.getCode())) {
                                data.put(ContractEnum.INVOICE_AMOUNT.getAttr(),Arith.sub(invoiceAmount,refIdMap.getOrDefault(id, 0D)));
                                data.put(ContractEnum.UN_INVOICE_AMOUNT.getAttr(),Arith.sub(amount,getDoubleOrDefaultFromFormData(data,ContractEnum.INVOICE_AMOUNT.getAttr(),0D)));
                                sourceData.put(ContractEnum.INVOICE_AMOUNT.getAttr(),Arith.sub(invoiceAmount,refIdMap.getOrDefault(id, 0D)));
                                sourceData.put(ContractEnum.UN_INVOICE_AMOUNT.getAttr(),Arith.sub(amount,getDoubleOrDefaultFromFormData(data,ContractEnum.INVOICE_AMOUNT.getAttr(),0D)));
                            }else if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT.getCode())) {
                                data.put(PaymentEnum.INVOICE_AMOUNT.getAttr(),Arith.sub(invoiceAmount,refIdMap.getOrDefault(id,0D)));
                                sourceData.put(PaymentEnum.INVOICE_AMOUNT.getAttr(),Arith.sub(invoiceAmount,refIdMap.getOrDefault(id,0D)));
                            } else if (Objects.equals(businessType, XbbRefTypeEnum.PAYMENT_SHEET.getCode())) {
                                data.put(PaymentSheetEnum.INVOICE_AMOUNT.getAttr(),Arith.sub(invoiceAmount,refIdMap.getOrDefault(id,0D)));
                                sourceData.put(PaymentSheetEnum.INVOICE_AMOUNT.getAttr(),Arith.sub(invoiceAmount,refIdMap.getOrDefault(id,0D)));
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 退货退款中关联回款单金额明细处理
     * @param parseSingleRowDataDTO 入参
     * @param result 回款单data
     * @param dataId 回款单Id
     * @throws XbbException error
     * @author zhouwq
     * @date 2019/12/18 15:07
     */
    private void paymentSheetAmountDetailHandleInRefund(ParseSingleRowDataDTO parseSingleRowDataDTO, JSONObject result, Long dataId, String corpid) throws XbbException {
        SheetAmountDetailGetDTO sheetAmountDetailGetDTO = new SheetAmountDetailGetDTO();
        BeanUtil.copyProperties(parseSingleRowDataDTO, sheetAmountDetailGetDTO);
        JSONArray contractArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(result, PaymentSheetEnum.CONTRACT.getAttr(), new JSONArray());
        JSONArray paymentArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(result, PaymentSheetEnum.PAYMENT.getAttr(), new JSONArray());
        JSONObject paySheetTypeObj = FastJsonHelper.getJsonObjectOrDefaultFromFormData(result, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr(), new JSONObject());
        String paySheetType = (paySheetTypeObj != null && paySheetTypeObj.get("value") != null) ? paySheetTypeObj.getString("value") : "";
        JSONObject accountObj = FastJsonHelper.getJsonObjectOrDefaultFromFormData(result, PaymentSheetEnum.FUND_ACCOUNT.getAttr(), new JSONObject());
        //原单非预收款核销（预收款核销的无资金账户），且原单有资金账户
        boolean flag = !Objects.equals(paySheetType, SheetTypeEnum.WRITE_OFF_PREPAYMENT.getCode()) && accountObj != null && accountObj.get("value") != null;
        if (flag) {
            accountObj.put("value", accountObj.get("value").toString());
        } else {
            //原单是预收款核销，或其他无资金账户的
            result.remove(PaymentSheetEnum.FUND_ACCOUNT.getAttr());
            //赋予默认资金账户
            FundAccountEntity fundAccountEntity = proFormHelp.getDefaultFundAccount(corpid, XbbRefTypeEnum.PAYMENT_SHEET);
            if (Objects.nonNull(fundAccountEntity)) {
                accountObj = new JSONObject();
                accountObj.put("text", fundAccountEntity.getName());
                //下拉类型前端都是用字符串接收
                accountObj.put("value", fundAccountEntity.getId().toString());
            }
            if (accountObj != null) {
                result.put(PaymentSheetEnum.FUND_ACCOUNT.getAttr(), accountObj);
            }
        }
        List<Long> contractIds = new ArrayList<>();
        List<Long> paymentIds = new ArrayList<>();
        if (contractArray.size() > 0) {
            for(Object obj : contractArray){
                if (obj instanceof JSONObject){
                    JSONObject contractObj = (JSONObject) obj;
                    contractIds.add(contractObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
                } else if (obj instanceof Integer) {
                    contractIds.add(Long.valueOf((Integer) obj));
                } else if (obj instanceof Long){
                    contractIds.add((Long) obj);
                }
            }
        }
        if (paymentArray.size() > 0) {
            for(Object obj : paymentArray){
                if (obj instanceof JSONObject){
                    JSONObject paymentObj = (JSONObject) obj;
                    paymentIds.add(paymentObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
                } else if (obj instanceof Integer) {
                    paymentIds.add(Long.valueOf((Integer) obj));
                } else if (obj instanceof Long){
                    paymentIds.add((Long) obj);
                }
            }
        }
        sheetAmountDetailGetDTO.setDataIdList(contractIds);
        sheetAmountDetailGetDTO.setPaymentIdList(paymentIds);
        sheetAmountDetailGetDTO.setLinkPreId(dataId);
        SheetAmountDetailGetVO sheetAmountDetailGetVO = saasPaymentHelper.paymentAmountDetailGet(false, sheetAmountDetailGetDTO);
        List<JSONObject> amountList = sheetAmountDetailGetVO.getList();
        result.put(PaasConstant.AMOUNTDETAIL, amountList);
        result.put(PaymentSheetEnum.AMOUNT.getAttr(), sheetAmountDetailGetVO.getSumAmount());
        if (amountList != null && amountList.size() > 0) {
            JSONArray linkContractArray = new JSONArray();
            List<Long> linkContractIdList = new ArrayList<>();
            JSONArray linkPaymentArray = new JSONArray();
            List<Long> linkPaymentIdList = new ArrayList<>();
            JSONArray linkBelongIdArray = new JSONArray();
            List<String> linkBelongIdList = new ArrayList<>();
            amountList.forEach(e -> {
                if (e.get(PaymentSheetEnum.PAYMENT.getAttr()) != null) {
                    JSONArray arrayP = e.getJSONArray(PaymentSheetEnum.PAYMENT.getAttr());
                    arrayP.forEach(obj -> {
                        JSONObject objP = (JSONObject) obj;
                        if (!linkPaymentIdList.contains(objP.getLong(StringConstant.SAAS_LINK_BUSINESS_ID))) {
                            linkPaymentArray.add(obj);
                            linkPaymentIdList.add(objP.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
                        }
                    });
                }
                if (e.get(PaymentSheetEnum.CONTRACT.getAttr()) != null) {
                    JSONArray arrayC = e.getJSONArray(PaymentSheetEnum.CONTRACT.getAttr());
                    arrayC.forEach(obj -> {
                        JSONObject objC = (JSONObject) obj;
                        if (!linkContractIdList.contains(objC.getLong(StringConstant.SAAS_LINK_BUSINESS_ID))) {
                            linkContractArray.add(obj);
                            linkContractIdList.add(objC.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
                        }
                    });
                }
                if (e.get(PaymentSheetEnum.BELONG_ID.getAttr()) != null) {
                    JSONArray arrayB = e.getJSONArray(PaymentSheetEnum.BELONG_ID.getAttr());
                    arrayB.forEach(obj -> {
                        JSONObject objB = (JSONObject) obj;
                        if (!linkBelongIdList.contains(objB.getString(StringConstant.SAAS_LINK_BUSINESS_ID))) {
                            linkBelongIdArray.add(obj);
                            linkBelongIdList.add(objB.getString(StringConstant.SAAS_LINK_BUSINESS_ID));
                        }
                    });
                }
            });
            result.put(PaymentSheetEnum.PAYMENT.getAttr(), linkPaymentArray);
            result.put(PaymentSheetEnum.CONTRACT.getAttr(), linkContractArray);
            result.put(PaymentSheetEnum.BELONG_ID.getAttr(), linkBelongIdArray);
        }
    }

    /**
     * 采购退货单中关联付款单金额明细处理
     * @param parseSingleRowDataDTO 入参
     * @param result 付款单data
     * @param dataId 付款单Id
     * @throws XbbException error
     * @author zhouwq
     * @date 2020/3/4 14:32
     */
    private void paySheetAmountDetailHandleInReturnedPurchase(ParseSingleRowDataDTO parseSingleRowDataDTO, JSONObject result, Long dataId, String corpid) throws XbbException {
        SheetAmountDetailGetDTO sheetAmountDetailGetDTO = new SheetAmountDetailGetDTO();
        BeanUtil.copyProperties(parseSingleRowDataDTO, sheetAmountDetailGetDTO);
        JSONArray purchaseArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(result, PaySheetEnum.LINK_PURCHASE.getAttr(), new JSONArray());
        JSONArray payArray = FastJsonHelper.getJsonArrOrDefaultFromFormData(result, PaySheetEnum.PAY_PLAN.getAttr(), new JSONArray());
        JSONObject paySheetTypeObj = FastJsonHelper.getJsonObjectOrDefaultFromFormData(result, PaySheetEnum.PAY_SHEET_TYPE.getAttr(), new JSONObject());
        String paySheetType = (paySheetTypeObj != null && paySheetTypeObj.get("value") != null) ? paySheetTypeObj.getString("value") : "";
        JSONObject accountObj = FastJsonHelper.getJsonObjectOrDefaultFromFormData(result, PaySheetEnum.FUND_ACCOUNT.getAttr(), new JSONObject());
        //原单非预付款核销（预付款核销的无资金账户），且原单有资金账户
        boolean flag = !Objects.equals(paySheetType, SheetTypeEnum.WRITE_OFF_PREPAY.getCode()) && accountObj != null && accountObj.get("value") != null;
        if (flag) {
            accountObj.put("value", accountObj.get("value").toString());
        } else {
            //原单是预付款核销，或其他无资金账户的
            result.remove(PaymentSheetEnum.FUND_ACCOUNT.getAttr());
            //赋予默认资金账户
            FundAccountEntity fundAccountEntity = proFormHelp.getDefaultFundAccount(corpid, XbbRefTypeEnum.PAY_SHEET);
            if (Objects.nonNull(fundAccountEntity)) {
                accountObj = new JSONObject();
                accountObj.put("text", fundAccountEntity.getName());
                //下拉类型前端都是用字符串接收
                accountObj.put("value", fundAccountEntity.getId().toString());
            }
            if (accountObj != null) {
                result.put(PaySheetEnum.FUND_ACCOUNT.getAttr(), accountObj);
            }
        }
        List<Long> purchaseIds = new ArrayList<>();
        List<Long> payIds = new ArrayList<>();
        if (purchaseArray.size() > 0) {
            for(Object obj : purchaseArray){
                if (obj instanceof JSONObject){
                    JSONObject purchaseObj = (JSONObject) obj;
                    purchaseIds.add(purchaseObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
                } else if (obj instanceof Integer) {
                    purchaseIds.add(Long.valueOf((Integer) obj));
                } else if (obj instanceof Long){
                    purchaseIds.add((Long) obj);
                }
            }
        }
        if (payArray.size() > 0) {
            for(Object obj : payArray){
                if (obj instanceof JSONObject){
                    JSONObject payObj = (JSONObject) obj;
                    payIds.add(payObj.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
                } else if (obj instanceof Integer) {
                    payIds.add(Long.valueOf((Integer) obj));
                } else if (obj instanceof Long){
                    payIds.add((Long) obj);
                }
            }
        }
        sheetAmountDetailGetDTO.setDataIdList(purchaseIds);
        sheetAmountDetailGetDTO.setPaymentIdList(payIds);
        sheetAmountDetailGetDTO.setLinkPreId(dataId);
        SheetAmountDetailGetVO sheetAmountDetailGetVO = saasPayPlanHelper.payAmountDetailGet(false, sheetAmountDetailGetDTO);
        List<JSONObject> amountList = sheetAmountDetailGetVO.getList();
        result.put(PaasConstant.AMOUNTDETAIL, amountList);
        result.put(PaySheetEnum.AMOUNT.getAttr(), sheetAmountDetailGetVO.getSumAmount());
        //将amountDetail中的归属人、关联
        if (amountList != null && amountList.size() > 0) {
            JSONArray linkPurchaseArray = new JSONArray();
            List<Long> linkPurchaseIdList = new ArrayList<>();
            JSONArray linkPayArray = new JSONArray();
            List<Long> linkPayIdList = new ArrayList<>();
            JSONArray linkBelongIdArray = new JSONArray();
            List<String> linkBelongIdList = new ArrayList<>();
            amountList.forEach(e -> {
                if (e.get(PaySheetEnum.PAY_PLAN.getAttr()) != null) {
                    JSONArray arrayP = e.getJSONArray(PaySheetEnum.PAY_PLAN.getAttr());
                    arrayP.forEach(obj -> {
                        JSONObject objP = (JSONObject) obj;
                        if (!linkPayIdList.contains(objP.getLong(StringConstant.SAAS_LINK_BUSINESS_ID))) {
                            linkPayArray.add(obj);
                            linkPayIdList.add(objP.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
                        }
                    });
                }
                if (e.get(PaySheetEnum.PURCHASE_LINK_TEXT.getAttr()) != null) {
                    JSONArray arrayC = e.getJSONArray(PaySheetEnum.PURCHASE_LINK_TEXT.getAttr());
                    arrayC.forEach(obj -> {
                        JSONObject objC = (JSONObject) obj;
                        if (!linkPurchaseIdList.contains(objC.getLong(StringConstant.SAAS_LINK_BUSINESS_ID))) {
                            linkPurchaseArray.add(obj);
                            linkPurchaseIdList.add(objC.getLong(StringConstant.SAAS_LINK_BUSINESS_ID));
                        }
                    });
                }
                if (e.get(PaySheetEnum.BELONG_ID.getAttr()) != null) {
                    JSONArray arrayB = e.getJSONArray(PaySheetEnum.BELONG_ID.getAttr());
                    arrayB.forEach(obj -> {
                        JSONObject objB = (JSONObject) obj;
                        if (!linkBelongIdList.contains(objB.getString(StringConstant.SAAS_LINK_BUSINESS_ID))) {
                            linkBelongIdArray.add(obj);
                            linkBelongIdList.add(objB.getString(StringConstant.SAAS_LINK_BUSINESS_ID));
                        }
                    });
                }
            });
            result.put(PaySheetEnum.PAY_PLAN.getAttr(), linkPayArray);
            result.put(PaySheetEnum.PURCHASE_LINK_TEXT.getAttr(), linkPurchaseArray);
            result.put(PaySheetEnum.BELONG_ID.getAttr(), linkBelongIdArray);
        }
    }

    /**
     * 将回/付款单流程数据插入到表单数据
     * @param processDataAddFormDataDTO 流程dto
     * @param paasFormDataEntity 实体
     * @param explainMap 字段解释map
     * @param data 数据data
     * @param businessType 回/付款单类型（已转换为具体类型的businessType）
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void processDataAddFormData4Sheet(ProcessDataAddFormDataDTO processDataAddFormDataDTO, PaasFormDataEntity paasFormDataEntity, Map<String, FieldAttrEntity> explainMap,
                                              JSONObject data, Integer businessType, List<FieldAttrEntity> fieldList) throws XbbException {
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = processDataAddFormDataDTO.getSaasNeedRedundantAttrPoJo();
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(processDataAddFormDataDTO, formDataAddDTO);
        formDataAddDTO.setBusinessType(businessType);
        formDataAddDTO.setDataList(data);
        formDataAddDTO.setSaasNeedRedundantAttrPoJo(saasNeedRedundantAttrPoJo);
        formDataAddDTO.setExplainMap(explainMap);
        OwnerIdAndCoUserIdUtil.setOwnIdAndCoUserId(data, formDataAddDTO, null);
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataAddDTO.getFormId(), formDataAddDTO.getCorpid());
        if ( paasFormEntityExt == null ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        if (saasNeedRedundantAttrPoJo != null) {
            //处理amoutDetail
            JSONArray amountDetailTemp = saasNeedRedundantAttrPoJo.getAmountDetail();
            if (CollectionUtils.isNotEmpty(amountDetailTemp)) {
                JSONArray amountDetail = new JSONArray();
                for (Object object : amountDetailTemp) {
                    JSONObject jsonObject1 = JSONObject.parseObject(JSONObject.toJSONString(object));
                    amountDetail.add(jsonObject1);
                }
                formDataAddDTO.setAmountDetail(amountDetail);
            }
        }
        formDataAddDTO.setProcessCreatorId(processDataAddFormDataDTO.getCreatorId());
        FormDataService abstractFormDataService = formDataServiceFactory.getFormDataService(formDataAddDTO.getBusinessType(), formDataAddDTO.getSaasMark());
        BeforeSaveVO beforeSaveVO = new BeforeSaveVO();
        beforeSaveVO.setPaasFormDataEntity(paasFormDataEntity);
        beforeSaveVO.setPaasFormEntityExt(paasFormEntityExt);
        beforeSaveVO.setSaasNeedRedundantAttrPojo(processDataAddFormDataDTO.getSaasNeedRedundantAttrPoJo());
        beforeSaveVO.setExplainMap(explainMap);
        beforeSaveVO.setExplainList(fieldList);
        beforeSaveVO.setNoApprovalRequired(1);
        SaveVO saveVO = abstractFormDataService.save(formDataAddDTO, beforeSaveVO, paasFormEntityExt, paasFormDataEntity);
        abstractFormDataService.afterSave(formDataAddDTO, beforeSaveVO, saveVO, paasFormEntityExt, paasFormDataEntity);
    }

    /**
     * 处理编号、关联原始应收、来源单据、初始化金额等
     * @param corpid 公司id
     * @param entityExt 原始应收实体
     * @param formDataId 原始应收id
     * @param data 原始应收data
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void handleRedReceivables4Refund(String corpid, PaasFormDataEntityExt entityExt, Long formDataId, JSONObject data) throws XbbException {
        //此处应收款自动生成了编号,但是不用根据之前的编号后面再加1
        String serialNo = fundHelp.handleRedReceivableSerialNo(Collections.singletonList(formDataId), corpid, entityExt.getSerialNo());
        Integer sourceBusinessType = FastJsonHelper.getIntegerOrDefaultFromFormData(data, PaymentEnum.SOURCE_REF_TYPE.getAttr(),0);
        Long source = FastJsonHelper.getLongOrDefaultFromFormData(data, PaymentEnum.SOURCE.getAttr(), null);
        Double unAmount = FastJsonHelper.getDoubleOrDefaultFromFormData(data, PaymentEnum.UN_AMOUNT.getAttr(), 0D);
        data.put(FieldTypeEnum.SERIALNO.getAlias(), serialNo);
        data.put(PaymentEnum.SOURCE_REF_TYPE.getAttr(), sourceBusinessType);
        data.put(PaymentEnum.SOURCE.getAttr(), source);
        data.put(PaymentEnum.RECEIVABLES_ORIGIN_ID.getAttr(), formDataId);
        data.put(PaymentEnum.RECEIVABLES_ORIGIN_LINK_TEXT.getAttr(), entityExt.getSerialNo());
        data.put(PaymentEnum.AMOUNT.getAttr(), unAmount);
        //先置为未收款（保存时会统一置为已红冲），因为只有未收款才能编辑编号、金额等
        data.put(PaymentEnum.STATUS.getAttr(), PaymentStatusEnum.UN_RECEIVABLES.getCode());
        //初始化其它字段
        for (Map.Entry<String,Object> entry : SaasDataInitHelp.initPayment().entrySet()){
            SaasDataInitHelp.antDataSet(data,entry.getKey(),entry.getValue());
        }
    }

    @Override
    public void updateOwner(HandoverDTO handoverDTO) throws XbbException {
        List<Long> idIn = handoverDTO.getDataIdList();
        String corpid = handoverDTO.getCorpid();
        String newOwnerId = handoverDTO.getHandoverUserId();
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(handoverDTO, true);
            param.put("ids", idIn);
            param.put("del", DelEnum.NORMAL.getDel());
            List<PaasFormDataEntityExt> paasFormDataEntityExtList = paasFormDataModel.findEntitys(param);
            if (Objects.isNull(paasFormDataEntityExtList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            for (PaasFormDataEntityExt paasFormDataEntityExt : paasFormDataEntityExtList) {
                paasFormDataEntityExt.setOwnerId(newOwnerId);
                paasFormDataModel.update(paasFormDataEntityExt);
            }
        } catch (Exception e) {
            LOG.error("paasFormDataServiceImpl.updateOwner 执行出错：", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
    }

    private Integer hasOuterLinkShare(Long formId, String corpid) throws XbbException{
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(ParameterConstant.CORPID, corpid);
        param.put(ParameterConstant.DEL, DelEnum.NORMAL.getDel());
        param.put("type", OuterLinkTypeEnum.SEARCH.getCode());
        param.put("formId", formId);
        List<OuterLinkEntity> entitys = outerLinkModel.findEntitys(param);
        if (CollectionsUtil.isNotEmpty(entitys)) {
            Integer enable = entitys.get(0).getEnable();
            if (Objects.equals(enable, BasicConstant.ONE)) {
                return enable;
            }
        }
        return 0;
    }

    private void setWaitOutstackFormExplain(PaasFormExplainEntity paasFormExplainEntity, FormDataListDTO formDataListDTO, PaasFormDataEsListVO formDataListVO) throws XbbException{
        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        PaasFormExplainEntity contractExplainEntity = paasFormExplainModel.getByFormId(formDataListDTO.getFormId(), formDataListDTO.getCorpid());
        List<FieldAttrEntity> contractExplainList = JSONArray.parseArray(contractExplainEntity.getExplains(), FieldAttrEntity.class);
        List<FieldAttrEntity> productExplainList=contractExplainList.stream().filter(fieldAttrEntity ->  Objects.equals(fieldAttrEntity.getAttr(), ContractEnum.PRODUCT.getAttr())
        ).collect(Collectors.toList());
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
        if (!productExplainList.isEmpty()){
            if(Objects.nonNull(productExplainList.get(0))){
                productExplainList.get(0).getSubForm().getItems().forEach((item) -> {
                    explainMap.put(item.getAttr(), item);
                });
            }
        }
        List<FieldAttrEntity> needExplainList = explainList.stream().filter(fieldAttrEntity -> Objects.equals(fieldAttrEntity.getAttr(), WaitInstockEnum.PRODUCT_IMGS.getAttr())
                || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.NAME.getAttr())
                || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.SERIALNO.getAttr())
                || Objects.equals(fieldAttrEntity.getAttr(), ProductEnum.SPECIFICATION.getAttr())
        ).collect(Collectors.toList());
        for (FieldAttrEntity fieldAttrEntity:needExplainList){
            if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.SERIALNO.getAttr())){
                fieldAttrEntity.setAttr(WaitOutstockEnum.PRODUCT_NO.getAttr());
                fieldAttrEntity.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
                fieldAttrEntity.setVisible(1);
                fieldAttrEntity.setVisibleScopeRule(new VisibleRulePoJo());
            }else if (Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.SPECIFICATION.getAttr())){
                fieldAttrEntity.setVisible(1);
                fieldAttrEntity.setAttr(WaitOutstockEnum.SPECIFICATION.getAttr());
                //fieldAttrEntity.setAttrName(WaitOutstockEnum.SPECIFICATION.getAttrName());
                fieldAttrEntity.setVisibleScopeRule(new VisibleRulePoJo());
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.NAME.getAttr())){
                if(Objects.nonNull(explainMap.get(ContractProductEnum.PRODUCT.getAttr()))){
                    FieldAttrEntity productAttr=explainMap.get(ContractProductEnum.PRODUCT.getAttr());
                    fieldAttrEntity.setAttrName(productAttr.getAttrName());
                }
                fieldAttrEntity.setAttr(WaitOutstockEnum.PRODUCT_NAME.getAttr());
                fieldAttrEntity.setVisible(1);
                fieldAttrEntity.setVisibleScopeRule(new VisibleRulePoJo());
                fieldAttrEntity.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
            }else if(Objects.equals(fieldAttrEntity.getAttr(),ProductEnum.PRODUCT_IMGS.getAttr())){
                fieldAttrEntity.setVisible(1);
                fieldAttrEntity.setVisibleScopeRule(new VisibleRulePoJo());
            }
            formDataListDTO.getExplainMap().put(fieldAttrEntity.getAttr(),fieldAttrEntity);
            formDataListVO.getExplainMap().put(fieldAttrEntity.getAttr(),fieldAttrEntity);
        }
        //新增待出库数量
        FieldAttrEntity availableStockAttr= new FieldAttrEntity();
        if (Objects.nonNull(explainMap.get(ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr()))){
            availableStockAttr=explainMap.get(ContractProductEnum.WAIT_OUTSTOCK_NUM.getAttr());
            availableStockAttr.setAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttr());
            availableStockAttr.setAttrName(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttrName());
            availableStockAttr.setSaasAttr("waitOutStockNum");
            availableStockAttr.setDisableListSort(0);
            availableStockAttr.setEditable(0);
            availableStockAttr.setVisible(1);
            availableStockAttr.setVisibleScopeRule(new VisibleRulePoJo());
        }else {
            FieldAttrEntity attr = formDataListDTO.getExplainMap().get(ProductEnum.NAME.getAttr());
            availableStockAttr = (FieldAttrEntity) CloneUtil.deepClone(attr);
            availableStockAttr.setAttr(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttr());
            availableStockAttr.setAttrName(WaitOutstockEnum.WAIT_OUTSTOCK_NUM.getAttrName());
            availableStockAttr.setSaasAttr("waitOutStockNum");
            availableStockAttr.setDisableListSort(0);
            availableStockAttr.setVisible(1);
            availableStockAttr.setEditable(0);
            availableStockAttr.setVisibleScopeRule(new VisibleRulePoJo());
        }
        //新增销售单位
        FieldAttrEntity unitAttr= new FieldAttrEntity();
        if (Objects.nonNull(explainMap.get(ContractProductEnum.UNIT.getAttr()))){
            unitAttr=explainMap.get(ContractProductEnum.UNIT.getAttr());
            unitAttr.setAttr(WaitOutstockEnum.UNIT.getAttr());
            //unitAttr.setAttrName(WaitOutstockEnum.UNIT.getAttrName());
            // 保持这个命名格式，别改成驼峰，否则会出问题
            unitAttr.setSaasAttr("product_unit");
            unitAttr.setEditable(0);
        }else {
            FieldAttrEntity attr = formDataListDTO.getExplainMap().get(ProductEnum.NAME.getAttr());
            unitAttr = (FieldAttrEntity) CloneUtil.deepClone(attr);
            unitAttr.setAttr(WaitOutstockEnum.UNIT.getAttr());
            unitAttr.setAttrName(WaitOutstockEnum.UNIT.getAttrName());
            // 保持这个命名格式，别改成驼峰，否则会出问题
            unitAttr.setSaasAttr("product_unit");
            unitAttr.setVisible(1);
            unitAttr.setVisibleScopeRule(new VisibleRulePoJo());
        }
        //新增库存数量
        FieldAttrEntity stockAttr= new FieldAttrEntity();
        if (Objects.nonNull(explainMap.get(ContractProductEnum.STOCK.getAttr()))){
            stockAttr=explainMap.get(ContractProductEnum.STOCK.getAttr());
            stockAttr.setAttr(WaitOutstockEnum.STOCK.getAttr());
            //stockAttr.setAttrName(WaitOutstockEnum.STOCK.getAttrName());
            stockAttr.setSaasAttr("stock");
            stockAttr.setEditable(0);
            stockAttr.setDisableListSort(1);
        }else {
            FieldAttrEntity attr = formDataListDTO.getExplainMap().get(ProductEnum.NAME.getAttr());
            stockAttr = (FieldAttrEntity) CloneUtil.deepClone(stockAttr);
            stockAttr.setAttr(WaitOutstockEnum.STOCK.getAttr());
            stockAttr.setAttrName(WaitOutstockEnum.STOCK.getAttrName());
            stockAttr.setSaasAttr("stock");
            stockAttr.setVisible(1);
            stockAttr.setVisibleScopeRule(new VisibleRulePoJo());
        }
        //新增备注字段
        FieldAttrEntity memoAttr = new FieldAttrEntity();
        if (Objects.nonNull(explainMap.get(ContractProductEnum.MEMO.getAttr()))) {
            memoAttr = explainMap.get(ContractProductEnum.MEMO.getAttr());
            memoAttr.setAttr(WaitOutstockEnum.MEMO.getAttr());
            memoAttr.setEditable(0);
            //memoAttr.setAttrName(WaitOutstockEnum.MEMO.getAttrName());
        } else {
            memoAttr = new FieldAttrEntity();
            memoAttr.setAttr(WaitInstockEnum.MEMO.getAttr());
            memoAttr.setAttrName(WaitInstockEnum.MEMO.getAttrName());
            memoAttr.setFieldType(WaitInstockEnum.MEMO.getFieldType());
            memoAttr.setSaasAttr(WaitInstockEnum.MEMO.getSaasAttr());
            memoAttr.setEditable(0);
            memoAttr.setLinkedType(WaitInstockEnum.MEMO.getLinkedType());
            memoAttr.setDisableListSort(0);
            memoAttr.setVisible(1);
            memoAttr.setVisibleScopeRule(new VisibleRulePoJo());
        }
        formDataListDTO.getExplainMap().put(availableStockAttr.getAttr(), availableStockAttr);
        formDataListVO.getExplainMap().put(availableStockAttr.getAttr(), availableStockAttr);
        formDataListDTO.getExplainMap().put(memoAttr.getAttr(), memoAttr);
        formDataListVO.getExplainMap().put(memoAttr.getAttr(), memoAttr);
        formDataListDTO.getExplainMap().put(unitAttr.getAttr(), unitAttr);
        formDataListVO.getExplainMap().put(unitAttr.getAttr(), unitAttr);
        formDataListDTO.getExplainMap().put(stockAttr.getAttr(), stockAttr);
        formDataListVO.getExplainMap().put(stockAttr.getAttr(), stockAttr);
        needExplainList.add(availableStockAttr);
        needExplainList.add(memoAttr);
        needExplainList.add(unitAttr);
        needExplainList.add(stockAttr);
        formDataListVO.getHeadList().addAll(needExplainList);
        //处理产品维度合同编号穿透
        for(FieldAttrEntity fieldAttrEntity : formDataListVO.getHeadList()){
            if (Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.CONTRACT_NO.getAttr()) ||
                    Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.NAME.getAttr())) {
                fieldAttrEntity.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
            }
            if(Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.CONTRACT_NO.getAttr()) ||
                    Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.NAME.getAttr())||
                    Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.LINK_CUSTOMER.getAttr())||
                    Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.SIGN_TIME.getAttr())||
                    Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.STATUS.getAttr())||
                    Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.OWNER_ID.getAttr())||
                    Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.MINOR_USER.getAttr())||
                    Objects.equals(fieldAttrEntity.getAttr(), WaitOutstockEnum.CREATOR_ID.getAttr())){
                fieldAttrEntity.setDisableListSort(1);
            }
            Integer sort = WaitOutstockEnum.getSortByWaitInstockSort(fieldAttrEntity.getAttr());
            fieldAttrEntity.setSort(sort);
        }
    }

    @Override
    public PaasFormDataEsListVO getContactSearchList(ContactSearchListDTO contactSearchListDTO) throws XbbException {
        PaasFormDataEsListVO formDataListVO;
        String corpid = contactSearchListDTO.getCorpid();
        Integer businessType = XbbRefTypeEnum.CONTACT.getCode();
        Integer sourceBusinessType = contactSearchListDTO.getSourceBusinessType();
        // 是否为左侧联系人列表
        Integer isLeftList = contactSearchListDTO.getIsLeftList();
        // （web端）是否为内部联系人，左侧联系人才有内部外部之分
        Integer internalContact = contactSearchListDTO.getInternalContact();
        // 只查询对应id的联系人
        List<Long> dataIdIn = contactSearchListDTO.getIdIn() != null ? contactSearchListDTO.getIdIn() : new ArrayList<>();
        Long customerId = contactSearchListDTO.getCustomerId();
        // 非左侧联系人＆左侧内部联系人，需要过虑节点中联系人
        List<Long> filterDataIdIn = contactSearchListDTO.getFilterDataIds();

        List<ConditionsEntityExt> conditionsEntityExtList = contactSearchListDTO.getConditions() != null ? contactSearchListDTO.getConditions() : new ArrayList<>();
        //解释
        PaasFormExplainEntity paasFormExplainEntity = paasFormExplainModel.getByBusinessType(businessType, corpid);
        if (Objects.isNull(paasFormExplainEntity) || Objects.equals(paasFormExplainEntity.getDel(),DelEnum.DELETE.getDel())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_EXPLAIN_NOT_EXIST);
        }
        Long formId = paasFormExplainEntity.getFormId();
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formId, corpid);
        if (Objects.isNull(paasFormEntityExt) || Objects.equals(paasFormEntityExt.getDel(), DelEnum.DELETE.getDel())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }

        List<FieldAttrEntity> explainList = JSONArray.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
        Map<String, FieldAttrEntity> explainMap = new HashMap<>(explainList.size());
        explainList.forEach((item) -> {
            explainMap.put(item.getAttr(), item);
        });

        BusinessDataDTO businessDataDTO = new BusinessDataDTO();
        BeanUtil.copyProperties(contactSearchListDTO, businessDataDTO);
        businessDataDTO.setBusinessType(businessType);
        businessDataDTO.setFormId(formId);
        businessDataDTO.setSaasMark(SaasMarkEnum.SAAS.getCode());
        businessDataDTO.setConditions(conditionsEntityExtList);
        // 联系人传入distributorMark=0
        businessDataDTO.setDistributorMark(DistributorMarkEnum.OTHER.getCode());


        FormDataListDTO formDataListDTO = new FormDataListDTO();
        BeanUtil.copyProperties(businessDataDTO, formDataListDTO, true);


        // 统一设置审批状态，默认只获取0（无需审批）,2（审批通过）状态的数据，有特殊的在specialHandleConditions中特殊设置
        formDataListDTO.getConditions().add(new ConditionsEntityExt(FieldTypeEnum.FLOW_STATUS.getAlias(), "", FieldTypeEnum.FLOW_STATUS.getType(), ConditionEnum.IN.getSymbol(), Arrays.asList(FlowStatusEnum.NOT_NEED_APPROVAL.getType(), FlowStatusEnum.PASS.getType())));
        // 只能搜到没有删除的数据
        formDataListDTO.setDel(0);
        // 回显的字段
        List<String> fieldList = Arrays.asList(ContactEnum.NAME.getAttr(), ContactEnum.PHONE.getAttr(), ContactEnum.CUSTOMER_NAME.getAttr(), ContactEnum.CUSTOMER_NAME_LINK_TEXT.getAttr());
//        formDataListDTO.setFieldList(fieldList);

        // 拼接条件：左侧列表中的外部联系人
        if (Objects.equals(BasicConstant.ONE, isLeftList) && Objects.equals(BasicConstant.TWO, internalContact)) {
            if (CollectionsUtil.isNotEmpty(dataIdIn)) {
                // 过虑传入为null
                dataIdIn.removeIf(Objects::isNull);
            }
            if (CollectionsUtil.isEmpty(dataIdIn)) {
                return new PaasFormDataEsListVO();
            }
            formDataListDTO.getConditions().add(EsUtil.packageContions(StringConstant.DATA_ID, new ArrayList<>(dataIdIn), ConditionEnum.IN, FieldTypeEnum.DATAID.getType()));
            formDataListDTO.setPageSize(dataIdIn.size());
        } else {
            // 过虑已添加到节点中的联系人ids
            if (CollectionsUtil.isNotEmpty(filterDataIdIn)) {
                // 过虑传入为null
                filterDataIdIn.removeIf(Objects::isNull);
            }
            if (CollectionsUtil.isNotEmpty(filterDataIdIn)) {
                formDataListDTO.getConditions().add(EsUtil.packageContions(StringConstant.DATA_ID, new ArrayList<>(filterDataIdIn), ConditionEnum.NOIN, FieldTypeEnum.DATAID.getType()));
            }
        }
        // 移动端机会决策树获取所有联系人（内部联系人＋外部联系人）
        String parentAttr = ContactEnum.CUSTOMER_NAME.getAttr();
        if (Objects.equals(XbbRefTypeEnum.SALES_OPPORTUNITY.getCode(), sourceBusinessType) && PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform())) {

        } else if (Objects.equals(BasicConstant.TWO, internalContact)) {

            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(parentAttr);
            conditionsEntityExt.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
            conditionsEntityExt.setName("");
            conditionsEntityExt.setSubAttr("");
            conditionsEntityExt.setSymbol(ConditionEnum.NOEQUAL.getSymbol());
            List<Object> valueList = new ArrayList<>();
            valueList.add(customerId.toString());
            conditionsEntityExt.setValue(valueList);
            formDataListDTO.getConditions().add(conditionsEntityExt);
        } else {
            if (dataIdIn != null) {
                dataIdIn.clear();
            }
            ConditionsEntityExt conditionsEntityExt = new ConditionsEntityExt();
            conditionsEntityExt.setAttr(parentAttr);
            conditionsEntityExt.setFieldType(FieldTypeEnum.LINK_BUSINESS_SINGLE.getType());
            conditionsEntityExt.setName("");
            conditionsEntityExt.setSubAttr("");
            conditionsEntityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
            List<Object> valueList = new ArrayList<>();
            valueList.add(customerId.toString());
            conditionsEntityExt.setValue(valueList);
            formDataListDTO.getConditions().add(conditionsEntityExt);
        }
        if (Objects.equals(BasicConstant.ZERO, isLeftList)) {
            // 更多联系人需要处理权限
            saasListDataPermissionHelp.listDataPermission(formDataListDTO.getConditions(), businessDataDTO.getLoginUser(), businessType, businessDataDTO.getSubBusinessType());
        }
        formDataListDTO.setExplainMap(explainMap);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(formDataListDTO.getCorpid(), formDataListDTO.getBusinessType(), formDataListDTO.getSaasMark());
        formDataListVO = paasFormDataEsModel.list(formDataListDTO, indexTypeEnum);

        formDataListVO.setHeadList(explainList);
        formDataListVO.setForm(paasFormEntityExt);
        if ( PlatFormEnum.WEB.getValue().equals(formDataListDTO.getPlatform()) ) {
            saasListHelp.analysisSaasDataList(formDataListVO, formDataListDTO.getExplainMap());

            if (Objects.equals(BasicConstant.ZERO, isLeftList)) {
                explainList = explainHelp.handleExplain(explainList, fieldList, paasFormEntityExt);
                formDataListVO.setHeadList(explainList);
            }
            // 返回数据处理
            // web端逻辑，主要处理下关于关联数据，用户，部门数据回显的问题
            //选择单据列表就不要这个了，不然会渲染操作栏
            formDataListDTO.setSubBusinessType(null);
            if (Objects.isNull(formDataListVO.getExplainMap())) {
                formDataListVO.setExplainMap(explainMap);
            }
            formDataListSearchHelp.webDataAnalysis(formDataListDTO, formDataListVO);
            formDataListVO = ExplainUtil.getValueByData(formDataListVO, formDataListDTO.getFormMap(), formDataListDTO.getFormIdAndHeadListMap());
        } else if ( PlatFormEnum.DINGTALK.getValue().equals(formDataListDTO.getPlatform()) ) {
            //app端需要对返回结果处理.
            //塞入summaryList, labelList,titleList。
            formDataListVO = formDataListSearchHelp.appDataAnalysis(formDataListDTO, formDataListVO);
            //按照业务类型塞入others,superScript;这里的逻辑是和列表展示保持一致的。eg: 关联客户数据 和 客户列表 的others逻辑是一样的
            formatBusinessDataAppList(formDataListDTO,formDataListVO.getPaasFormDataESList());
        }
        // 头像处理
        saasListHelp.setOnlyDBData(formDataListDTO, formDataListVO);
        // 数据摘要、数据标签数据处理
        decisionTreeHelp.handleSummaryList(formDataListVO.getPaasFormDataESList(), explainMap, contactSearchListDTO.getLoginUser());

        // 新建权限
        VerifyAddPermissionDTO verifyAddPermissionDTO = new VerifyAddPermissionDTO();
        BeanUtil.copyProperties(businessDataDTO, verifyAddPermissionDTO);
        verifyAddPermissionDTO.setBusinessType(businessType);
        verifyAddPermissionDTO.setMenuId(paasFormExplainEntity.getMenuId());
        verifyAddPermissionDTO.setSaasMark(paasFormExplainEntity.getSaasMark());
        List<ButtonPojo> buttonList = paasFormHelp.getAddButton(verifyAddPermissionDTO, paasFormExplainEntity.getAppId(), paasFormExplainEntity.getFormId());
        formDataListVO.setTopPermissions(buttonList);

        return formDataListVO;
    }

    /**
     * paas表单进工作流的时候对团队的操作
     *
     * @param saasFormSaveDTO
     */
    @Override
    public void afterSaveForWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException{
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        JSONObject newData = saasFormSaveDTO.getNewData();
        teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(),saasFormSaveDTO.getNewPaasFormDataEntity().getId(),newPaasFormDataEntity,saasFormSaveDTO.getIsImport(),true);
    }

    @Override
    public AfterSavePojo afterSave(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        // 团队保存
        return teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(), saasFormSaveDTO.getNewPaasFormDataEntity().getId(), saasFormSaveDTO.getNewPaasFormDataEntity(), saasFormSaveDTO.getIsImport(), false);
    }

    @Override
    public void afterSaveForUpdateWorkflow(SaasFormSaveDTO saasFormSaveDTO) throws XbbException {
        PaasFormDataEntity newPaasFormDataEntity = saasFormSaveDTO.getNewPaasFormDataEntity();
        teamDataHelp.saveUserTeam(saasFormSaveDTO.getSaasNeedRedundantAttrPoJo(),saasFormSaveDTO.getNewPaasFormDataEntity().getId(), newPaasFormDataEntity,saasFormSaveDTO.getIsImport(),true);
    }

    @Override
    public CheckTransferDateVO checkTransferDate(CheckTransferDateDTO checkTransferDateDTO) throws XbbException {
        CheckTransferDateVO checkTransferDateVO = new CheckTransferDateVO();
        checkTransferDateVO.setIsRemind(fundHelp.checkTransferDate(checkTransferDateDTO.getCorpid(),checkTransferDateDTO.getTransferDate()));
        return checkTransferDateVO;
    }

    /**
     * @Author: wujian
     * @Description: 校验当前日期之后是否有新单据
     * @Date:  2022/5/30
     * @Param: [checkDateDTO]
     * @return: com.xbongbong.pro.formdata.pojo.vo.CheckDateVO
     **/
    @Override
    public CheckDateVO checkDate(CheckDateDTO checkDateDTO) throws XbbException {
        CheckDateVO checkDateVO = new CheckDateVO();
        String corpid = checkDateDTO.getCorpid();
        Long date = checkDateDTO.getDate();
        List<Long> productIdList = checkDateDTO.getProductIdList();
        if (Objects.isNull(date) || CollectionUtils.isEmpty(productIdList)){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.DATE_PRODUCTID_NOT_NULL)));
        }
        StockFlowBillEntity stockFlowBillEntity = stockFlowBillModel.checkDate(corpid, date,productIdList);
        if (Objects.nonNull(stockFlowBillEntity)){
            checkDateVO.setIsHint(1);
        }else {
            checkDateVO.setIsHint(0);
        }
        return checkDateVO;
    }


    /**
     * @Author: wujian
     * @Description: 删除时校验单据之后是否有流水
     * @Date: 下午2:53 2022/5/31
     * @Param: [checkDateDTO]
     * @return: com.xbongbong.pro.formdata.pojo.vo.CheckDateVO
     **/
    @Override
    public CheckDateVO deleteCheckDate(CheckDateDTO checkDateDTO) throws XbbException {
        CheckDateVO checkDateVO = new CheckDateVO();
        checkDateVO.setIsHint(0);
        String corpid = checkDateDTO.getCorpid();
        Integer businessType = checkDateDTO.getBusinessType();
        XbbRefTypeEnum xbbRefTypeEnum = XbbRefTypeEnum.getByCode(businessType);
        List<String> nameList = new ArrayList<>();
        Long date = 0L;
        List<Long> productIdList = new ArrayList<>();
        List<Long> dataIdList = checkDateDTO.getDataIdList();
        String message = "";
        String s = " \" ";
        if (CollectionUtils.isEmpty(dataIdList)){
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.DATE_PRODUCTID_NOT_NULL)));
        }
        // 单个删除
        if (Objects.equals(dataIdList.size(),1)){
            Long dataId = checkDateDTO.getDataIdList().get(0);
            if (Objects.isNull(dataId)){
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100002, String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.DATE_PRODUCTID_NOT_NULL)));
            }
            date = formatSingleDelCheck(corpid,dataId,xbbRefTypeEnum,date,productIdList);
            if (CollectionUtils.isNotEmpty(productIdList)){
                StockFlowBillEntity stockFlow = stockFlowBillModel.checkDate(corpid, date, productIdList);
                List<Long> inconformityProductIdList = new ArrayList<>();
                // 如果有则 说明有插单的
                if (Objects.nonNull(stockFlow)){
                    List<StockFlowBillEntity> stockFlowBillEntityList = stockFlowBillModel.getCheckDate(corpid, date, productIdList);
                    if (CollectionUtils.isNotEmpty(stockFlowBillEntityList)){
                        for (StockFlowBillEntity stockFlowBillEntity : stockFlowBillEntityList) {
                            if (inconformityProductIdList.size() < 5){
                                inconformityProductIdList.add(stockFlowBillEntity.getProductId());
                            }
                        }
                    }

                }else {
                    // 如果没大于当前时间的 再去查询是否有等于当前单据日期的
                    Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    param.put(ParameterConstant.CORPID, corpid);
                    param.put("date", date);
                    param.put(ParameterConstant.DEL, 0);
                    param.put("productIdIn",productIdList);
                    List<StockFlowBillEntity> entitys = stockFlowBillModel.findEntitys(param);
                    Long lastId = 0L;
                    if (CollectionUtils.isNotEmpty(entitys)){
                        Iterator<StockFlowBillEntity> iterator = entitys.iterator();
                        while (iterator.hasNext()){
                            StockFlowBillEntity stockFlowBillEntity = iterator.next();
                            Long id = stockFlowBillEntity.getId();
                            Long refId = stockFlowBillEntity.getRefId();
                            // 找到当前单据中最晚生成流水的ID
                            if (Objects.equals(refId,dataId)){
                                if (id > lastId){
                                    lastId = id;
                                }
                                iterator.remove();
                            }
                        }
                        if (CollectionUtils.isNotEmpty(entitys)){
                            for (StockFlowBillEntity entity : entitys) {
                                Long id = entity.getId();
                                if (id > lastId && inconformityProductIdList.size() < 5){
                                    inconformityProductIdList.add(entity.getProductId());
                                }
                            }
                        }
                    }

                }
                if (CollectionUtils.isNotEmpty(inconformityProductIdList)){
                    List<ProductEntityExt> productListByIdIn = productModel.getProductListByIdIn(corpid, inconformityProductIdList, 0);
                    if (CollectionUtils.isNotEmpty(productListByIdIn)){
                        for (ProductEntityExt productEntityExt : productListByIdIn) {
                            JSONObject productData = productEntityExt.getData();
                            if (Objects.nonNull(productData)){
                                String productName = productData.getString(ProductEnum.NAME.getAttr());
                                nameList.add(productName);
                            }
                        }
                    }
                }

            }
            if(CollectionUtils.isNotEmpty(nameList)){
                checkDateVO.setIsHint(1);
                StringBuffer nameBuffer = new StringBuffer();
                for (String name : nameList) {
                    nameBuffer.append(s).append(name).append(s);
                }
                message = "删除该单据后，可能会触发插单操作导致" + nameBuffer + "的成本异常(如出现负成本)，是否继续该操作？";
            }
        }else {
            // 批量删除
            Map<Long,Long> dateMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,List<Long>> productIdListMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            Map<Long,String> serialNoMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);

            Map<String, Object> delParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            delParam.put(ParameterConstant.CORPID, corpid);
            delParam.put(ParameterConstant.DEL, 0);
            delParam.put("idIn", dataIdList);
            // 删除单据时单据中最晚的时间
            Long lastTime = 0L;
            switch (xbbRefTypeEnum){
                case OTHER_OUTSTOCK:
                case CONTRACT_OUTSTOCK:
                case PRODUCTION_MATERIEL_OUTSTOCK:
                case WORK_ORDER_OUTSTOCK:
                case RETURNED_PURCHASE_OUTSTOCK:
                    List<OutstockEntityExt> outstockEntityExtList = outstockModel.findEntitys(delParam);
                    if (CollectionUtils.isNotEmpty(outstockEntityExtList)){
                        for (OutstockEntityExt outstockEntityExt : outstockEntityExtList) {
                            JSONObject data = outstockEntityExt.getData();
                            if (Objects.nonNull(data) && Objects.nonNull(data.get(OutstockEnum.TIME.getAttr()))){
                                dateMap.put(outstockEntityExt.getId(),data.getLong(OutstockEnum.TIME.getAttr()));
                            }
                            serialNoMap.put(outstockEntityExt.getId(),outstockEntityExt.getSerialNo());
                        }
                    }
//                    List<OutstockProductEntity> outstockProductEntities = outstockProductModel.getProductsByOutstockIdIn(corpid, dataIdList);
//                    if (CollectionUtils.isNotEmpty(outstockProductEntities)){
//                        for (OutstockProductEntity outstockProductEntity : outstockProductEntities) {
//                            Long outStockId = outstockProductEntity.getOutWarehouseId();
//                            Long productId = outstockProductEntity.getProductId();
//                            if (productIdListMap.containsKey(outStockId)){
//                                List<Long> list = productIdListMap.get(outStockId);
//                                list.add(productId);
//                                productIdListMap.put(outStockId,list);
//                            }else {
//                                List<Long> productIds = new ArrayList<>();
//                                productIds.add(productId);
//                                productIdListMap.put(outStockId,productIds);
//                            }
//                        }
//                    }
                    break;
                case OTHER_INSTOCK:
                case PURCHASE_INSTOCK:
                case PRODUCTION_INSTOCK:
                case RETURNED_MATERIEL_INSTOCK:
                case REFUND_INSTOCK:
                    List<InstockEntityExt> instockEntityExtList = instockModel.findEntitys(delParam);
                    if (CollectionUtils.isNotEmpty(instockEntityExtList)){
                        for (InstockEntityExt instockEntityExt : instockEntityExtList) {
                            JSONObject data = instockEntityExt.getData();
                            if (Objects.nonNull(data) && Objects.nonNull(data.get(InstockEnum.TIME.getAttr()))){
                                dateMap.put(instockEntityExt.getId(),data.getLong(InstockEnum.TIME.getAttr()));
                            }
                            serialNoMap.put(instockEntityExt.getId(),instockEntityExt.getSerialNo());
                        }
                    }
//                    List<InstockProductEntity> instockProductEntityList = instockProductModel.getProductsByInstockIdIn(corpid, dataIdList);
//                    if (CollectionUtils.isNotEmpty(instockProductEntityList)){
//                        for (InstockProductEntity instockProductEntity : instockProductEntityList) {
//                            Long inStockId = instockProductEntity.getIntoWarehouseId();
//                            Long productId = instockProductEntity.getProductId();
//                            if (productIdListMap.containsKey(inStockId)){
//                                List<Long> list = productIdListMap.get(inStockId);
//                                list.add(productId);
//                                productIdListMap.put(inStockId,list);
//                            }else {
//                                List<Long> productIds = new ArrayList<>();
//                                productIds.add(productId);
//                                productIdListMap.put(inStockId,productIds);
//                            }
//                        }
//                    }
                    break;
                case TRANSFER:
                    List<TransferEntityExt> transferEntityExtList = transferModel.findEntitys(delParam);
                    if (CollectionUtils.isNotEmpty(transferEntityExtList)){
                        for (TransferEntityExt transferEntityExt : transferEntityExtList) {
                            JSONObject data = transferEntityExt.getData();
                            if (Objects.nonNull(data) && Objects.nonNull(data.get(TransferEnum.TRANSFER_TIME.getAttr()))){
                                dateMap.put(transferEntityExt.getId(),data.getLong(TransferEnum.TRANSFER_TIME.getAttr()));
                            }
                            serialNoMap.put(transferEntityExt.getId(),transferEntityExt.getSerialNo());
                        }
                    }
//                    List<TransferProductEntity> transferProductEntityList = transferProductModel.getProductsByTransferIdIn(corpid, dataIdList);
//                    if (CollectionUtils.isNotEmpty(transferProductEntityList)){
//                        for (TransferProductEntity transferProductEntity : transferProductEntityList) {
//                            Long transferId = transferProductEntity.getTransferId();
//                            Long productId = transferProductEntity.getProductId();
//                            if (productIdListMap.containsKey(transferId)){
//                                List<Long> list = productIdListMap.get(transferId);
//                                list.add(productId);
//                                productIdListMap.put(transferId,list);
//                            }else {
//                                List<Long> productIds = new ArrayList<>();
//                                productIds.add(productId);
//                                productIdListMap.put(transferId,productIds);
//                            }
//                        }
//                    }
                    break;
                case INVENTORY:
                    List<InventoryEntityExt> inventoryModelEntitys = inventoryModel.findEntitys(delParam);
                    if (CollectionUtils.isNotEmpty(inventoryModelEntitys)){
                        for (InventoryEntityExt inventoryEntityExt : inventoryModelEntitys) {
                            JSONObject data = inventoryEntityExt.getData();
                            if (Objects.nonNull(data) && Objects.nonNull(data.get(InventoryEnum.TIME.getAttr()))){
                                dateMap.put(inventoryEntityExt.getId(),data.getLong(InventoryEnum.TIME.getAttr()));
                            }
                            serialNoMap.put(inventoryEntityExt.getId(),inventoryEntityExt.getSerialNo());
                        }
                    }
//                    Map<String, Object> inventoryParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//                    inventoryParam.put(ParameterConstant.CORPID, corpid);
//                    inventoryParam.put(ParameterConstant.DEL, 0);
//                    inventoryParam.put("inventoryIdIn", dataIdList);
//                    List<InventoryProductEntity> inventoryProductEntityList = inventoryProductModel.findEntitys(inventoryParam);
//                    if (CollectionUtils.isNotEmpty(inventoryProductEntityList)){
//                        for (InventoryProductEntity inventoryProductEntity : inventoryProductEntityList) {
//                            Long inventoryId = inventoryProductEntity.getInventoryId();
//                            Long productId = inventoryProductEntity.getProductId();
//                            if (productIdListMap.containsKey(inventoryId)){
//                                List<Long> list = productIdListMap.get(inventoryId);
//                                list.add(productId);
//                                productIdListMap.put(inventoryId,list);
//                            }else {
//                                List<Long> productIds = new ArrayList<>();
//                                productIds.add(productId);
//                                productIdListMap.put(inventoryId,productIds);
//                            }
//                        }
//                    }
                    break;
                case ASSEMBLE:
                    List<AssembleEntityExt> assembleModelEntitys = assembleModel.findEntitys(delParam);
                    if (CollectionUtils.isNotEmpty(assembleModelEntitys)){
                        for (AssembleEntityExt assembleEntityExt : assembleModelEntitys) {
                            JSONObject data = assembleEntityExt.getData();
                            if (Objects.nonNull(data) && Objects.nonNull(data.get(AssembleEnum.ASSEMBLE_TIME.getAttr()))){
                                dateMap.put(assembleEntityExt.getId(),data.getLong(AssembleEnum.ASSEMBLE_TIME.getAttr()));
                            }
                            serialNoMap.put(assembleEntityExt.getId(),assembleEntityExt.getSerialNo());
                        }
                    }
//                    Map<String, Object> assembleParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
//                    assembleParam.put(ParameterConstant.CORPID, corpid);
//                    assembleParam.put(ParameterConstant.DEL, 0);
//                    assembleParam.put("assembleIdIn", dataIdList);
//                    List<AssembleProductEntity> assembleproductList = assembleProductModel.findEntitys(assembleParam);
//                    if (CollectionUtils.isNotEmpty(assembleproductList)){
//                        for (AssembleProductEntity assembleProductEntity : assembleproductList) {
//                            Long assembleIdId = assembleProductEntity.getAssembleId();
//                            Long productId = assembleProductEntity.getProductId();
//                            if (productIdListMap.containsKey(assembleIdId)){
//                                List<Long> list = productIdListMap.get(assembleIdId);
//                                list.add(productId);
//                                productIdListMap.put(assembleIdId,list);
//                            }else {
//                                List<Long> productIds = new ArrayList<>();
//                                productIds.add(productId);
//                                productIdListMap.put(assembleIdId,productIds);
//                            }
//                        }
//                    }
                    break;
                case COST_ADJUST:
                    List<CostAdjustEntityExt> costAdjustModelEntitys = costAdjustModel.findEntitys(delParam);
                    if (CollectionUtils.isNotEmpty(costAdjustModelEntitys)){
                        for (CostAdjustEntityExt costAdjustEntityExt : costAdjustModelEntitys) {
                            JSONObject data = costAdjustEntityExt.getData();
                            if (Objects.nonNull(data) && Objects.nonNull(data.get(CostAdjustEnum.ADJUST_TIME.getAttr()))){
                                dateMap.put(costAdjustEntityExt.getId(),data.getLong(CostAdjustEnum.ADJUST_TIME.getAttr()));
                            }
                            serialNoMap.put(costAdjustEntityExt.getId(),costAdjustEntityExt.getSerialNo());
                        }
                    }
//                    List<CostAdjustProductEntity> costAdjustProductEntityList = costAdjustProductModel.getProductsByAdjustIdIn(corpid, dataIdList);
//                    if(CollectionUtils.isNotEmpty(costAdjustProductEntityList)){
//                        for (CostAdjustProductEntity costAdjustProductEntity : costAdjustProductEntityList) {
//                            Long costAdjustId = costAdjustProductEntity.getCostAdjustId();
//                            Long productId = costAdjustProductEntity.getProductId();
//                            if (productIdListMap.containsKey(costAdjustId)){
//                                List<Long> list = productIdListMap.get(costAdjustId);
//                                list.add(productId);
//                                productIdListMap.put(costAdjustId,list);
//                            }else {
//                                List<Long> productIds = new ArrayList<>();
//                                productIds.add(productId);
//                                productIdListMap.put(costAdjustId,productIds);
//                            }
//                        }
//                    }
                    break;
            }
            if (!dateMap.isEmpty()){
                for (Long value : dateMap.values()) {
                    if (value > lastTime){
                        lastTime = value;
                    }
                }
                StockFlowBillEntity firstStockFlowBillBytime = stockFlowBillModel.getFirstStockFlowBillBytime(corpid, lastTime);
                if (Objects.nonNull(firstStockFlowBillBytime)){
                    checkDateVO.setIsHint(1);
                    message = "批量删除单据时，可能会触发插单操作导致产品成本异常（如出现负成本），是否继续该操作？";
                }
            }
        }
        checkDateVO.setMessage(message);
        checkDateVO.setNameList(nameList);
        return checkDateVO;
    }


    private Long formatSingleDelCheck(String corpid,Long dataId,XbbRefTypeEnum xbbRefTypeEnum,Long date,List<Long> productIdList){
        switch (xbbRefTypeEnum){
            case OTHER_OUTSTOCK:
            case CONTRACT_OUTSTOCK:
            case PRODUCTION_MATERIEL_OUTSTOCK:
            case WORK_ORDER_OUTSTOCK:
            case RETURNED_PURCHASE_OUTSTOCK:
                OutstockEntityExt outstockEntityExt = outstockModel.getByKey(dataId, corpid);
                if (Objects.nonNull(outstockEntityExt)){
                    JSONObject data = outstockEntityExt.getData();
                    if (Objects.nonNull(data) && Objects.nonNull(data.get(OutstockEnum.TIME.getAttr()))){
                        date = data.getLong(OutstockEnum.TIME.getAttr());
                    }
                    Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    param.put(ParameterConstant.CORPID, corpid);
                    param.put("outWarehouseId", dataId);
                    param.put(ParameterConstant.DEL, 0);
                    param.put(ParameterConstant.COLUMNS, "id ,product_id");
                    List<OutstockProductEntity> outstockProductEntityList = outstockProductModel.findEntitys(param);
                    if (CollectionUtils.isNotEmpty(outstockProductEntityList)){
                        outstockProductEntityList.forEach(item -> productIdList.add(item.getProductId()));
                    }
                }
                break;
            case OTHER_INSTOCK:
            case PURCHASE_INSTOCK:
            case PRODUCTION_INSTOCK:
            case RETURNED_MATERIEL_INSTOCK:
            case REFUND_INSTOCK:
                InstockEntityExt instockEntityExt = instockModel.getByKey(dataId, corpid);
                if (Objects.nonNull(instockEntityExt)){
                    JSONObject instockData = instockEntityExt.getData();
                    if (Objects.nonNull(instockData) && Objects.nonNull(instockData.get(InstockEnum.TIME.getAttr()))){
                        date = instockData.getLong(InstockEnum.TIME.getAttr());
                    }
                    Map<String, Object> instockParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    instockParam.put(ParameterConstant.CORPID, corpid);
                    instockParam.put("intoWarehouseId", dataId);
                    instockParam.put(ParameterConstant.DEL, 0);
                    instockParam.put(ParameterConstant.COLUMNS, "id ,product_id");
                    List<InstockProductEntity> instockProductEntityList = instockProductModel.findEntitys(instockParam);
                    if (CollectionUtils.isNotEmpty(instockProductEntityList)){
                        instockProductEntityList.forEach(item -> productIdList.add(item.getProductId()));
                    }
                }
                break;
            case TRANSFER:
                TransferEntityExt transferEntityExt = transferModel.getByKey(dataId, corpid);
                if (Objects.nonNull(transferEntityExt)){
                    JSONObject transferData = transferEntityExt.getData();
                    if (Objects.nonNull(transferData) && Objects.nonNull(transferData.get(TransferEnum.TRANSFER_TIME.getAttr())) && Objects.equals(transferData.getInteger(TransferEnum.STATUS.getAttr()), TransferStatusEnum.ALREADY_OUT_INSTOCK.getCode())){
                        date = transferData.getLong(TransferEnum.TRANSFER_TIME.getAttr());
                        List<TransferProductEntity> transferProducts = transferProductModel.getProductsByTransferId(dataId, corpid);
                        if (CollectionUtils.isNotEmpty(transferProducts)){
                            transferProducts.forEach(item -> productIdList.add(item.getProductId()));
                        }
                    }
                }
                break;
            case INVENTORY:
                InventoryEntityExt inventoryEntityExt = inventoryModel.getByKey(dataId, corpid);
                if (Objects.nonNull(inventoryEntityExt)){
                    JSONObject inventoryData = inventoryEntityExt.getData();
                    if (Objects.nonNull(inventoryData) && Objects.nonNull(inventoryData.get(InventoryEnum.TIME.getAttr())) && Objects.equals(inventoryData.getInteger(InventoryEnum.STATUS.getAttr()), InventoryStatusEnum.ALREADY_OUT_INSTOCK.getCode())){
                        date = inventoryData.getLong(InventoryEnum.TIME.getAttr());
                        List<InventoryProductEntity> inventoryProducts = inventoryProductModel.getProductsByInventoryId(dataId, corpid);
                        if (CollectionUtils.isNotEmpty(inventoryProducts)){
                            inventoryProducts.forEach(item -> productIdList.add(item.getProductId()));
                        }
                    }
                }
                break;
            case ASSEMBLE:
                AssembleEntityExt assembleEntityExt = assembleModel.getByKey(dataId, corpid);
                if (Objects.nonNull(assembleEntityExt)){
                    JSONObject assembleData = assembleEntityExt.getData();
                    if (Objects.nonNull(assembleData) && Objects.nonNull(assembleData.get(AssembleEnum.ASSEMBLE_TIME.getAttr()))){
                        date = assembleData.getLong(AssembleEnum.ASSEMBLE_TIME.getAttr());
                        List<AssembleProductEntity> assembleProducts = assembleProductModel.getProductsByAssembleId(dataId, corpid);
                        if (CollectionUtils.isNotEmpty(assembleProducts)){
                            assembleProducts.forEach(item -> productIdList.add(item.getProductId()));
                        }
                    }
                }
                break;
            case COST_ADJUST:
                CostAdjustEntityExt costAdjustEntityExt = costAdjustModel.getByKey(dataId, corpid);
                if (Objects.nonNull(costAdjustEntityExt) && Objects.nonNull(costAdjustEntityExt.getData()) && Objects.nonNull(costAdjustEntityExt.getData().get(CostAdjustEnum.ADJUST_TIME.getAttr()))){
                    date = costAdjustEntityExt.getData().getLong(CostAdjustEnum.ADJUST_TIME.getAttr());
                }
                List<CostAdjustProductEntity> costAdjustProducts = costAdjustProductModel.getProductsByAdjustIdIn(corpid, Collections.singletonList(dataId));
                if (CollectionUtils.isNotEmpty(costAdjustProducts)){
                    costAdjustProducts.forEach(item -> productIdList.add(item.getProductId()));
                }
                break;
            case ORI_STOCK:
                Map<String, Object> oriParam = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                oriParam.put(ParameterConstant.CORPID, corpid);
                oriParam.put("id", dataId);
                oriParam.put(ParameterConstant.DEL, 0);
                oriParam.put(ParameterConstant.COLUMNS, "id ,product_id");
                List<WarehouseOristockEntity> oristockEntityList = warehouseOristockModel.findEntitys(oriParam);
                // 期初里面的时间是当天开始的00:00
                if (CollectionUtils.isNotEmpty(oristockEntityList)){
                    Long addTime = oristockEntityList.get(0).getAddTime();
                    date = DateTimeUtil.getStartOfDay(addTime);
                }
                List<WarehouseOristockProductEntity> oriProducts = warehouseOristockProductModel.getProductsByOriStockIdIn(corpid, Collections.singletonList(dataId));
                if(CollectionUtils.isNotEmpty(oriProducts)){
                    oriProducts.forEach(item -> productIdList.add(item.getProductId()));
                }
                break;
        }
        return date;
    }
}
